The ls() Function in R

The ls() Function in R

Basic Usage

The ls() function retrieves the names of objects in a given environment. By default, it lists objects in the global environment. 

# Define some variables
a <- 1
b <- 2
c <- 3
# List objects in the global environment
ls()  # Returns "a" "b" "c"

Arguments of ls()

  • name: Specifies the environment from which to list objects. By default, ls() uses the global environment.
# List objects in a specific environment
my_env <- new.env()
assign("x", 10, envir = my_env)
ls(envir = my_env)  # Returns "x"
  • pattern: A regular expression to filter the names of objects. Only objects with names matching the pattern are returned.
# Define more variables
apple <- 1
orange <- 2
# List objects with names containing "ap"
ls(pattern = "ap")  # Returns "apple"
  • all.names: Logical value indicating whether to include objects starting with a dot (hidden objects). The default is FALSE.
# Define a hidden variable
.hidden <- 100
# List objects including hidden ones
ls(all.names = TRUE)  # Returns ".hidden" "a" "b" "c"

Environments and ls()

ls() can be used to list objects in different environments, not just the global environment. 

# Create a new environment
my_env <- new.env()
assign("foo", 42, envir = my_env)
assign("bar", 99, envir = my_env)
# List objects in the new environment
ls(envir = my_env)  # Returns "foo" "bar"

Using ls() with Packages

You can also use ls() to list objects in the environments of packages that are currently loaded. 

# Load the dplyr package
library(dplyr)
# List objects in the dplyr package environment
ls("package:dplyr")  # Lists functions and objects in the dplyr package

Examples

Listing Objects in a Specific Environment 

# Define a new environment
local_env <- new.env()
local_env$a <- 1
local_env$b <- 2
# List objects in the local environment
ls(envir = local_env)  # Returns "a" "b"

Filtering Object Names 

# Define variables
data1 <- 10
data2 <- 20
other <- 30
# List objects whose names start with "data"
ls(pattern = "^data")  # Returns "data1" "data2"

Practical Use Cases

  • Debugging: Quickly identify which objects are available in the current environment or a specific environment.
  • Package Exploration: Explore functions and datasets within a loaded package.
  • Clean-up: Determine which objects are present before performing environment clean-up.

Summary

  • Basic Functionality: Lists object names in the specified environment.
  • Arguments: name (environment), pattern (regex filter), all.names (include hidden objects).
  • Environments: Works with global, custom, and package environments.
  • Use Cases: Debugging, package exploration, and environment management.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Facebook
Twitter
LinkedIn
WhatsApp
Email
Print