Shuo
Shuo

Reputation: 491

R split out list based on name

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.

Upvotes: 3

Views: 3044

Answers (3)

Roman Luštrik
Roman Luštrik

Reputation: 70633

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.

Upvotes: 2

IRTFM
IRTFM

Reputation: 263382

 blah <- list()
 for (i in 1:10) {
   blah[['a']][i] <- i;  blah[['b']][i] <- i+10
   }

 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

Upvotes: 0

Andriy T.
Andriy T.

Reputation: 2030

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
}

Upvotes: 1

Related Questions