Create Named List in R (2 Examples)
In this R post you’ll learn how to construct a named list object.
Table of contents:
Let’s dive right into the programming part.
Example 1: Create Named List from Scratch
In this example, I’ll demonstrate how to initialize a new named list from scratch.
For this task, we can use the list() function as shown below:
my_list1 <- list(Name1 = 1:5, # Create a named list Name2 = letters[3:1], Name3 = "asdf") my_list1 # Print a named list # $Name1 # [1] 1 2 3 4 5 # # $Name2 # [1] "c" "b" "a" # # $Name3 # [1] "asdf"
Have a look at the previous output of the RStudio console: It shows that we have constructed a list with three different list elements. You can also see that each of these list elements has a name.
Example 2: Create Named List from Two Vectors
This section explains how to create a list object based on two vectors of names and values.
As a first step, we have to create such vectors:
vec_values <- 1:5 # Create vector of values vec_values # Print vector of values # [1] 1 2 3 4 5
vec_names <- paste0("Name", 1:5) # Create vector of names vec_names # Print vector of names # [1] "Name1" "Name2" "Name3" "Name4" "Name5"
Next, we can apply the setNames and as.list functions to create a named list from our name and value pairs:
my_list2 <- setNames(as.list(vec_values), # Convert vectors to named list vec_names) my_list2 # Print a named list # $Name1 # [1] 1 # # $Name2 # [1] 2 # # $Name3 # [1] 3 # # $Name4 # [1] 4 # # $Name5 # [1] 5
Video, Further Resources & Summary
In case you need more information on the R programming syntax of this article, you might watch the following video on my YouTube channel. In the video, I explain the contents of this post.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Additionally, you could have a look at the other articles on https://statisticsglobe.com/.
- Create List of Installed Packages
- Create List with Single Value in R
- Create List with Names but no Entries
- Create Nested List in R
- R Programming Examples
To summarize: You have learned in this article how to build a named list object in the R programming language. In case you have additional questions, let me know in the comments.
Statistics Globe Newsletter