theforestecologist
theforestecologist

Reputation: 4917

Quickly find value from data.frame in list with matching element names

I have a list with xnumber of named elements, with each element containing a series of numbers.

I also have a data.frame containing 2 columns:

I want to quickly determine the location of the value of each row of my data.frame in the list given that the list element equals each given data.frame row's value in the data.frame's name column.

The end goal is actually to produce a vector containing the list value of each appropriate element preceding the value I've matched for each row of my data.frame.

My data has 200,000 rows so I'm trying to optimize this process.


Example

I have a list and data.frame:

a = 1:5; b = 6:10; c = 4:8; l1 <- list(a,b,c) # a list
d1 <- data.frame(name = c('c','a','b'), val = c(7,3,8)) #a data.frame

So first I want to know where each value occurs in the list (such that the element matches the name from the same row in the data.frame) :

where <- ????

>where
[1] 4 3 3     # 7 = 4th number in c, 3 = 3rd # in a, and 8 = 3rd # in b

But ultimately I want the output to show me the value in the element preceding the one I've matched:

which <- ????

>which
[1] 6 2 7

Upvotes: 2

Views: 3669

Answers (1)

HubertL
HubertL

Reputation: 19544

To have a list with named items, you can use this syntax:

l1 <- list(a=a,b=b,c=c)

Then you can use mapply() to test each item:

mapply(function(n,v) which(l1[[n]]==v) , d1$name,d1$val)
[1] 4 3 3

Then mapply() again to get values:

mapply(function(n,i) l1[[ n]][i] , d1$name,
    mapply(function(n,v) which(l1[[n]]==v)-1 , d1$name,d1$val))
[1] 6 2 7

Upvotes: 5

Related Questions