Question

I have a list with a depth equal 2. I would like to subscript that list as described in the following example:

my.list<-list(
  a=list(
    a1=1:10,
    a2=11:20),
  b=list(
    b1=21:30,
    b2=31:40),
  c=list(
    c1=41:50,
    c2=51:60)
)
# choose a specific item 
my.list[[2]][[2]][[3]]

# choose all first items from a1,a2,b1,b2,c1,c2
test<-list()
for(i in 1:3)
  for (j in 1:2)test[[i]][[j]]<-my.list[[i]][[j]][[1]]

test

Error in `*tmp*`[[i]] : subscript out of bounds

But this won't work since the list I created has no lists within it. What works is to do like this:

test<-list()
for(i in 1:3)
  for (j in 1:2)test[[i]]<-my.list[[i]][[j]][[1]]

and then

test<-list()
for(i in 1:3)
  for (j in 1:2)test[[i]][[j]]<-my.list[[i]][[j]][[1]]

test

gives:

[[1]]
[1]  1 11

[[2]]
[1] 21 31

[[3]]
[1] 41 51

...

Was it helpful?

Solution

Does the following code solve your problem?

lapply(my.list, sapply, head, 1)

gives you the first element of each vector for each entry in my.list:

$a
a1 a2 
 1 11 

$b
b1 b2 
21 31 

$c
c1 c2 
41 51 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top