What is the ls() function in R?
Overview
The ls() function in R is used to return a vector of character strings containing all the variables and functions that are defined in the current working directory in R programming.
Variables whose names begin with a dot are, by default, not returned. To change this behavior, we set all.names to TRUE.
Syntax
ls(name, pos = -1L, envir = as.environment(pos),all.names = FALSE, pattern, sorted = TRUE)
Syntax for the ls()) function in R
Parameter value
The ls() function takes the following optional parameter values.
name: This is the environment used in listing the available objects.pos: This is an alternative argument to the parameternamefor specifying the environment as a position in the search list.envir: This is another alternative argument tonamefor specifying the environment.all.names: This takes a logical value (TRUEorFALSE) indicating whether all the object names are returned (ifTRUE) or the object names beginning with a.are omitted (ifFALSE.)
pattern: Only names that match thepatternare returned.sorted: This takes a logical value (TRUEorFALSE) indicating if the outputcharactershould be sorted alphabetically or not.
Code
# creating R variables and functionsa <- 36b <- sqrt(a)c <- a*b.hide <- "ls will not show this if all.names= FALSE"# implementing the ls() function by defaultls()# implementing the ls() function to omit variables begining with dot(.)ls(all.names='FALSE')# implementing the ls() function to also return variables begining with (.)ls(all.names='TRUE')
Explanation
- Lines 2–5: We create the variables
a,b,c, and.hide.
- Line 8: We call the
ls()function without passing an argument to the function. - Line 11: We call the
ls()function to return all the variables, except for the ones starting with a dot. - Line 14: We call the
ls()function to return all the variables, including the ones starting with a dot.