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 parameter name for specifying the environment as a position in the search list.
  • envir: This is another alternative argument to name for specifying the environment.
  • all.names: This takes a logical value (TRUE or FALSE) indicating whether all the object names are returned (if TRUE) or the object names beginning with a . are omitted (if FALSE.)
  • pattern: Only names that match the pattern are returned.
  • sorted: This takes a logical value (TRUE or FALSE) indicating if the output character should be sorted alphabetically or not.

Code

# creating R variables and functions
a <- 36
b <- sqrt(a)
c <- a*b
.hide <- "ls will not show this if all.names= FALSE"
# implementing the ls() function by default
ls()
# 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.

Free Resources