adam.888
adam.888

Reputation: 7846

R: select from nested list by ID

I have a nested list where the first term contains the ID and the other terms contains characteristics associated with that ID:

list3  = list(list("a","b","c","d","e","f"), list(1:6), list(c(10,20,30,40,50,60))
list3

I would like to then select from this list by ID to just get the terms associated with that ID : I tried:

ID="e"
listselect <- list3[list3[[1]]==ID]
listselect 

But this does not work. I was hoping to get just the terms associated with e: listselect: e, 5,50

I would be grateful for your help.

Upvotes: 4

Views: 274

Answers (4)

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

You can proceed with:

x = 'e'

lapply(list3[-1], function(u) u[[1]][which(list3[[1]]==x)])

#[[1]]
#[1] 5

#[[2]]
#[1] 50

Or even neater:

rapply(list3[-1], `[[`, ...=which(list3[[1]]==x), how="unlist")

Upvotes: 4

arvi1000
arvi1000

Reputation: 9582

Colonel Beauvel's answer is good, but I'll add: this is a case where you really want a data.frame and not a list of lists.

# the data
list3  = list(list("a","b","c","d","e","f"), list(1:6), list(seq(10,60,10)))

# convert to data.frame and fix names
df3 <- data.frame(lapply(list3, unlist))
names(df3) <- paste0('v', 1:ncol(df3))

# now you can do this - so easy!
df3[df3[, 1] == 'e', ]

Result:

  v1 v2 v3
5  e  5 50

Upvotes: 4

Colin Robinson
Colin Robinson

Reputation: 144

You need to index the list appropriately to get what you want. Your command listselect <- list3[list3[[1]]==ID] returns FALSE FALSE FALSE FALSE TRUE FALSE which is the same as returning "5", so when you index list3[5] you get the fifth list in the nested list, which doesn't exist in your case. If you want to get the part of each list associated with e, you'd have to either index them separately as in c(list3[[2]][list3[[1]]==ID], list3[[3]][list3[[1]]==ID]) or loop through the length of list3 as in list3[[i]][list3[[1]]==ID] and save those to listselect as you go.

Upvotes: 1

Mike Wise
Mike Wise

Reputation: 22827

Maybe you want this:

 list3  = list(list("a","b","c","d","e","f"), 1:6, 10*(1:6))

Then you can get these:

 lidx <- list3[[1]]=="e"
 list3[[2]][lidx] 
 # [1] 5
 list3[[3]][lidx]
 # [1] 50

Upvotes: 1

Related Questions