Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R split out list based on name

Tags:

list

r

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.

like image 343
Shuo Avatar asked Jul 03 '26 08:07

Shuo


2 Answers

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.

like image 134
Roman Luštrik Avatar answered Jul 05 '26 23:07

Roman Luštrik


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
}
like image 38
Andriy T. Avatar answered Jul 05 '26 23:07

Andriy T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!