Using the ls() Function in R
Syntax
ls(name = NULL, envir = .GlobalEnv, all.names = FALSE, pattern = NULL)
- name: Specifies the name of an environment from which to list objects. By default, this is NULL, meaning the global environment (.GlobalEnv) is used.
- envir: The environment to search for objects. By default, it is the global environment (.GlobalEnv).
- all.names: Logical value. If TRUE, includes objects with names that start with a dot (.). By default, this is FALSE.
- pattern: A regular expression to filter objects by names matching the given pattern.
Basic Usage
To list all objects in the global environment:
# Create some objects a <- 1 b <- "test" c <- matrix(1:4, nrow = 2) # List objects ls() # Returns a character vector with object names: "a", "b", "c"
Listing Objects with Names Starting with a Dot
By default, objects with names starting with a dot (.) are not listed. To include them, use all.names = TRUE.
# Create objects with names starting with a dot .hidden <- 42 .visible <- "hello" # List objects including those starting with a dot ls(all.names = TRUE) # Returns ".hidden", ".visible"
Listing Objects in a Specific Environment
To list objects in a specific environment, use the envir argument.
# Create a specific environment my_env <- new.env() my_env$var1 <- 10 my_env$var2 <- "example" # List objects in the specific environment ls(envir = my_env) # Returns "var1", "var2"
Filtering Objects with a Regular Expression
You can use the pattern argument to filter objects by a specific pattern.
# Create objects data1 <- 1 data2 <- 2 info1 <- "info" info2 <- "data" # List objects whose names contain "data" ls(pattern = "data") # Returns "data1", "data2"
Practical Examples
List All Objects
# Create some objects x <- 5 y <- c(1, 2, 3) df <- data.frame(a = 1:3, b = letters[1:3]) # List all objects ls() # Returns "x", "y", "df"
Include Hidden Objects
# Create objects with hidden names .hidden_obj <- "secret" visible_obj <- "visible" # List all objects, including hidden ones ls(all.names = TRUE) # Returns ".hidden_obj", "visible_obj"
List Objects in a Specific Environment
# Create a new environment and add objects special_env <- new.env() special_env$a <- 100 special_env$b <- "example" # List objects in the "special_env" environment ls(envir = special_env) # Returns "a", "b"
Filter by Pattern
# Create some objects item1 <- "first" item2 <- "second" other <- "different" # List objects whose names contain "item" ls(pattern = "item") # Returns "item1", "item2"
Summary
The ls() function is essential for exploring and managing your R workspace. It allows you to list objects present in the global environment or any other specified environment. With the all.names and pattern arguments, you can refine the list to include hidden objects and filter by specific patterns. This functionality is useful for managing and navigating through objects in your R session.