Create Named List from Two Vectors of Names & Values in R (Example Code)

This article demonstrates how to construct a named list in R programming.

Creation of Example Data

x1 <- 1:4                                 # Constructing a vector of values
x1
# [1] 1 2 3 4
x2 <- paste0("my_name_", LETTERS[1:4])    # Constructing a vector of names
x2
# [1] "my_name_A" "my_name_B" "my_name_C" "my_name_D"

Example: Creating a Named List from Two Vectors of Values & Names

x12_list <- setNames(as.list(x1),         # Create named list from vectors
                     x2)
x12_list
# $my_name_A
# [1] 1
# 
# $my_name_B
# [1] 2
# 
# $my_name_C
# [1] 3
# 
# $my_name_D
# [1] 4

Related Articles & Further Resources

Have a look at the following R programming tutorials. They focus on similar topics as this post:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top