0

I am wondering how to convert lists to vectors in R where each vector comprises of an element of an element of the list. In particular, I would like the 1st vector to comprise of the 1st element of each element of the list. I would like the 2nd vector to comprise of the 2nd element of each element of the list. More generally, I would like the nth vector to comprise of the nth element of each element of the list. Thus, n will equal the length of the longest element of the list.

For example, suppose we had:

mylist = list(c("a", "b"), c(character(0)), c(1, 2, 3))

I would like to create three vectors where

first_vector = c("a", NA, 1)
second_vector = c("b", NA, 2)
third_vector = c(NA, NA, 3)

As you can see in the above example, I may have additional complications due to missing values.

Thank you so much in advance for help!

-Vincent

Vincent
  • 7,808
  • 13
  • 49
  • 63

2 Answers2

5

Usually creating endless amount of objects in your global environment is bad practice, and since all your vectors are of the same length, you could just create one matrix instead

indx <- max(lengths(mylist))
sapply(mylist, `length<-`, indx)
#     [,1] [,2] [,3]
# [1,] "a"  NA   "1" 
# [2,] "b"  NA   "2" 
# [3,] NA   NA   "3" 
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
  • Thank you for your help! What does `...` do in R? – Vincent Jan 06 '15 at 19:47
  • Take a look [here](http://stackoverflow.com/questions/3057341/how-to-use-rs-ellipsis-feature-when-writing-your-own-function) Or [here](http://stackoverflow.com/questions/5890576/usage-of-three-dots-or-dot-dot-dot-in-functions) – David Arenburg Jan 06 '15 at 19:50
  • Oh, I'm sorry. I meant to ask what does the character before length<- do? It seems to be a single quotation mark? – Vincent Jan 06 '15 at 19:56
  • It tells R that this is a function, rather I'm trying to insert something into an object called `length`, take look [here](http://stackoverflow.com/questions/10449366/levels-what-sorcery-is-this) – David Arenburg Jan 06 '15 at 19:58
3

You could also consider stri_list2matrix from the "stringi" package. Depending on the orientation desired:

library(stringi)
stri_list2matrix(mylist)
#      [,1] [,2] [,3]
# [1,] "a"  NA   "1" 
# [2,] "b"  NA   "2" 
# [3,] NA   NA   "3" 

stri_list2matrix(mylist, byrow = TRUE)
#      [,1] [,2] [,3]
# [1,] "a"  "b"  NA  
# [2,] NA   NA   NA  
# [3,] "1"  "2"  "3" 
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485