How to access specific parts of a list in R?

r
lists
list

#1

Hello,

Suppose I have a list ‘lp’ in R. I want to access its elements like we access columns from a data frame. For example, I have elements in this way->

[[1]]
[1] “a” “b”

[[2]]
[1] “c” “d”

[[3]]
[1] “e” “f”

[[4]]
[1] “g” “h”

[[5]]
[1] “i” “j”

and so on…
I want to place all elements a,c,e,g,i… in one separate column and other elements b,d,f,h,j… in other column. How can I do this?


#2

This seems to work.

> lp <- c(list(c("a", "b")), list(c("c", "d")), list(c("e", "f")), list(c("g", "h")))
> lp
[[1]]
[1] "a" "b"

[[2]]
[1] "c" "d"

[[3]]
[1] "e" "f"

[[4]]
[1] "g" "h"

> tlpdf = t(as.data.frame(lp, optional = TRUE))
> colnames(tlpdf) = c("A", "B")
> rownames(tlpdf) = 1:4
> tlpdf
  A   B  
1 "a" "b"
2 "c" "d"
3 "e" "f"
4 "g" "h"

#3

Good solution anon. You can simplify the naming commands into one:

dimnames(tlpdf) <- list(1:4, c('A', 'B'))

#4

This is another way of doing it

x<-matrix(unlist(lp),byrow=T,nrow = length(lp))

x
[,1] [,2]
[1,] “a” “b”
[2,] “c” “d”
[3,] “e” “f”
[4,] “g” “h”