ls & objects Functions in R (2 Examples)
This article shows how to return a vector of character strings giving the names of the objects in an environment using the ls and objects functions in the R programming language.
Table of contents:
Note that the ls() and objects() functions are basically applied the same way. In the present tutorial, I will use only the ls() function, but if you want you may replace it by the objects() function.
Let’s start right away!
Example 1: Apply ls() Function when Environment is Empty
In this example, I’ll explain how to apply the ls() function in R.
Note that we have not created any data objects in our global environment yet.
Let’s use the ls function:
ls() # Apply ls function # character(0)
As you can see based on the previous output of the RStudio console, the ls function has returned an empty character string, indicating that our workspace is empty.
Example 2: Apply ls() Function to Return Names of Objects in Environment
The following code illustrates how to use the ls() function when the environment is not empty.
For this, we first have to create some data objects in R:
x1 <- 1 # Create data objects x2 <- 2 x3 <- 3
Next, let’s apply the ls function once again:
ls() # Apply ls function #  "x1" "x2" "x3"
The RStudio console returns the names of our data objects as character strings.
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. I explain the R syntax of this page in the video:
The YouTube video will be added soon.
Furthermore, you could read the other articles on my website. I have released several tutorials already:
- What’s the Difference between rm() & rm(list=ls())?
- Print All Data Objects in Workspace
- Garbage Collection with gc() Function
- The Difference Between the rm & gc Functions
- Built-in R Commands (+ Examples)
- All R Programming Tutorials
In summary: This tutorial has demonstrated how to apply the ls() and objects() functions in the R programming language. Don’t hesitate to let me know in the comments below, in case you have any further questions.
Statistics Globe Newsletter