You can use one of the following methods to convert a list to a vector in R:
#use unlist() function new_vector <- unlist(my_list, use.names = FALSE) #use flatten_*() function from purrr library new_vector <- purrr::flatten(my_list)
The following examples show how to use each of these methods in practice with the following list:
#create list my_list <- list(A = c(1, 2, 3), B = c(4, 5), C = 6) #display list my_list $A [1] 1 2 3 $B [1] 4 5 $C [1] 6
Example 1: Convert List to Vector Using unlist() Function
The following code shows how to convert a list to a vector using the unlist() function:
#convert list to vector new_vector <- unlist(my_list) #display vector new_vector A1 A2 A3 B1 B2 C 1 2 3 4 5 6
Note that you can specify use.names = FALSE to remove the names from the vector:
#convert list to vector new_vector <- unlist(my_list, use.names = FALSE) #display vector new_vector [1] 1 2 3 4 5 6
Example 2: Convert List to Vector Using flatten_* Function
The following code shows how to convert a list to a vector using the family of flatten_* functions from the purrr package:
library(purrr) #convert list to vector new_vector <- flatten_dbl(my_list) #display vector new_vector [1] 1 2 3 4 5 6
The flatten_dbl() function specifically converts the list to a vector of type double.
Note that we could use flatten_chr() to convert a character list to a vector of type character:
library(purrr) #define character list my_char_list <- list(A = c('a', 'b', 'c'), B = c('d', 'e'), C = 'f') #convert character list to character vector new_char_vector <- flatten_chr(my_char_list) #display vector new_char_vector [1] "a" "b" "c" "d" "e" "f"
Check out this page for a complete list of the family of flatten_* functions.
Note: If you’re working with an extremely large list, the flatten_* functions will perform quicker than the unlist() function from base R.
Additional Resources
How to Convert List to a Data Frame in R
How to Convert Matrix to Vector in R
How to Convert Data Frame Column to Vector in R