Suppose I create the following structure
blah <- c()
for (i in 1:10) {
blah <- c(blah,list(a=i,b=i+10))
}
I want blah$a to be a vector of (1,2,3,4,5,6,7,8,9,10) and blah$b to be a vector of (11,12,13,14,15,16,17,18,19,20).
For the life of me, I can't figure out how to do this.
I think this should work. I first split your list according to the names of elements and then "unlist" the list of list inside each list element. You can also unname each vector (not shown). See code:
lapply(split(x = blah, f = names(blah)), unlist)
$a
a a a a a a a a a a
1 2 3 4 5 6 7 8 9 10
$b
b b b b b b b b b b
11 12 13 14 15 16 17 18 19 20
In comments, @David mentions
split(unlist(blah), names(blah))
which also works and is probably more efficient.
Actually you can avoid loops:
blah <- list(a = 1:10, b = 1:10+10)
And you get this:
# > blah
# $a
# [1] 1 2 3 4 5 6 7 8 9 10
#
# $b
# [1] 11 12 13 14 15 16 17 18 19 20
# > blah$a
# [1] 1 2 3 4 5 6 7 8 9 10
with loop:
for (i in 1:10) {
blah$a[i] <- i
blah$b[i] <- i+10
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With