All entities in R are called objects. They can be arrays, numbers, strings, functions. In this tutorial we look at how to list all objects in R.
function name :
objects()
or
ls()
the objects() or ls() function can be used to get a vector of character strings of the names of all objects in the environment.
>objects() character(0) # empty, no objects present >a=c(1,2,3) >objects() [1] "a" # shows object a just created >
The names in the result are sorted.
By default the objects returned are from the environment from which ls() or objects() is called. It is possible to specify a different environment name. For example, if called within a function the objects returned are from the function scope. However it is possible to get all object in the global scope by using the .GlobalEnv environment.
f1 <- function() { a1=c(1,2,3) ls() }
function f1 creates an object a1. the ls function returns that object
> f1() [1] "a1"
Function f2 creates an object but lists all objects from the global scope
f2 <- function() { a1=c(1,2,3) ls(envir=.GlobalEnv) } > f2() [1] "a" "d" "f1" "f2" "z"
the objects a,d,z were created earlier and f1,f2 are functions. Since we have specified global scope, calling function f2 returns not only objects from the function scope but also objects from the global scope.
It is also possible to list objects that specify a particular regular expression
The code below returns all objects whose name contains an f
> ls(pattern="f") [1] "f1" "f2"
The code below returns all objects whose name ends with "1"
> ls(pattern="1$") [1] "f1
This completes our tutorial on listing Objects in R. In the next tutorial we will see how to run R code contained in a file.
These are not listing objects. They are listing the “names” of the objects, in other words, you can’t retrieve object through these lists. You should explain how to list objects directly and how to retrieve them.