You can use the as.list() function to quickly convert a vector to a list in R.
This function uses the following basic syntax:
my_list <- as.list(my_vector)
The following example shows how to use this function in practice.
Example: Convert Vector to List in R
The following code shows how to use the as.list() function to convert a vector to a list:
#create vector
my_vector <- c('A', 'B', 'C', 'D')
#convert vector to list
my_list <- as.list(my_vector)
#view list
my_list
[[1]]
[1] "A"
[[2]]
[1] "B"
[[3]]
[1] "C"
[[4]]
[1] "D"
We can use the class() function to confirm that the new object indeed has a class of list:
#view class of list
class(my_list)
[1] "list"
Bonus: Append Vector to List
You might think that you could use the following syntax to append the elements of a vector to a list in R:
#attempt to create list with 6 elements some_list <- list('A', 'B', as.list(c('C', 'D', 'E', 'F'))) #view list some_list [[1]] [1] "A" [[2]] [1] "B" [[3]] [[3]][[1]] [1] "C" [[3]][[2]] [1] "D" [[3]][[3]] [1] "E" [[3]][[4]] [1] "F"
Rather than a list with six elements, the list has three elements and the third element has four sub-elements.
To append the elements of a vector to a list, we must use the following code:
#define vector
my_vector <- c('C', 'D', 'E', 'F')
#define first list
list1 <- list('A', 'B')
#convert vector to second list
list2 <- as.list(my_vector)
#create long list by combining first list and second list
list3 <- c(list1, list2)
#view result
list3
[[1]]
[1] "A"
[[2]]
[1] "B"
[[3]]
[1] "C"
[[4]]
[1] "D"
[[5]]
[1] "E"
[[6]]
[1] "F"
The result is a list with six elements.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Convert List to Vector in R
How to Convert Matrix to Vector in R
How to Convert Data Frame Column to Vector in R