Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: select from nested list by ID

Tags:

list

r

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.

like image 697
adam.888 Avatar asked Dec 25 '22 17:12

adam.888


2 Answers

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")
like image 93
Colonel Beauvel Avatar answered Jan 07 '23 14:01

Colonel Beauvel


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
like image 23
arvi1000 Avatar answered Jan 07 '23 15:01

arvi1000