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.
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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With