T. Beige T. Beige - 14 days ago 5
R Question

Access to list elements in R

I have got a list of 1300 lists in R. Something like this example:

Example = list(list(A = 1, B=data.frame(x = 2, y = 2), C="Test"), list(A = 2, B=data.frame(x = 1, y = 2), C="Test2"), list(A = 3, B=data.frame(x = 3, y = 8), C="Test3"))

> Beispiel
[[1]]
[[1]]$A
[1] 1

[[1]]$B
x y
1 2 2

[[1]]$C
[1] "Test"

[[2]]
[[2]]$A
[1] 2

[[2]]$B
x y
1 1 2

[[2]]$C
[1] "Test2"

[[3]]
[[3]]$A
[1] 3

[[3]]$B
x y
1 3 8

[[3]]$C
[1] "Test3"


Now, I need a
data.frame
like this:

rbind(Beispiel[[1]]$B, Beispiel[[2]]$B, Beispiel[[3]]$B)


The problem is, that it does not work with a command like

rbind(Beispiel[[1:3]]$B)


Any idea how I can get a data.frame without naming every list?

Answer

Loop over the list using lapply to extract the desired element of each sublist:

do.call(rbind, lapply(Example, "[[", "B"))
#  x y
#1 2 2
#2 1 2
#3 3 8
Comments