Store List of Lists in Data Matrix in R (Example Code)
In this R programming article you’ll learn how to convert nested lists to data frames and matrices.
Introduction of Example Data
list_no1 <- list(c("X", "A", "F"), # List No. 1 "XXX") list_no1 # [[1]] # [1] "X" "A" "F" # # [[2]] # [1] "XXX" # |
list_no1 <- list(c("X", "A", "F"), # List No. 1 "XXX") list_no1 # [[1]] # [1] "X" "A" "F" # # [[2]] # [1] "XXX" #
list_no2 <- list(7:2, # List No. 2 55) list_no2 # [[1]] # [1] 7 6 5 4 3 2 # # [[2]] # [1] 55 # |
list_no2 <- list(7:2, # List No. 2 55) list_no2 # [[1]] # [1] 7 6 5 4 3 2 # # [[2]] # [1] 55 #
list_of_lists <- list(list_no1, # Nested list list_no2) list_of_lists # Display nested list in RStudio # [[1]] # [[1]][[1]] # [1] "X" "A" "F" # # [[1]][[2]] # [1] "XXX" # # # [[2]] # [[2]][[1]] # [1] 7 6 5 4 3 2 # # [[2]][[2]] # [1] 55 # # |
list_of_lists <- list(list_no1, # Nested list list_no2) list_of_lists # Display nested list in RStudio # [[1]] # [[1]][[1]] # [1] "X" "A" "F" # # [[1]][[2]] # [1] "XXX" # # # [[2]] # [[2]][[1]] # [1] 7 6 5 4 3 2 # # [[2]][[2]] # [1] 55 # #
Example: Convert Nested List in Data Matrix
data_of_lists <- do.call(cbind, list_of_lists) # Apply do.call & cbind data_of_lists # Display lists in data matrix # [,1] [,2] # [1,] Character,3 Integer,6 # [2,] "XXX" 55 |
data_of_lists <- do.call(cbind, list_of_lists) # Apply do.call & cbind data_of_lists # Display lists in data matrix # [,1] [,2] # [1,] Character,3 Integer,6 # [2,] "XXX" 55
Further Resources & Related Articles
Here, you can find some further resources on topics such as factors, data conversion, and character strings.