Reputation: 93
I have a data frame and a list which is as such:
> df
value
1 5
2 25
3 6
4 70
And list:
> y
[[1]]
[1] 5 6 70 25
[[2]]
[1] 6 70 5 25
How do I make the list return the index of each elements such that it is:
> y
[[1]]
[1] 1 3 4 2
[[2]]
[1] 3 4 1 2
Upvotes: 2
Views: 52
Reputation: 269586
Assuming the data in the Note at the end:
Map(match, y, df)
giving:
[[1]]
[1] 1 3 4 2
[[2]]
[1] 3 4 1 2
Not needed with the data here, but if your df
actually has more than one column specify that the value
column is the one to use like this:
Map(match, y, df["value"])
Lines <- " value
1 5
2 25
3 6
4 70"
df <- read.table(text = Lines)
y <- list(c(5, 6, 70, 25), c(6, 70, 5, 25))
Upvotes: 2
Reputation: 887118
We can use match
to get the index by looping over the list
and matching with the 'value' column of 'df'
lapply(y, function(x) match(x, df$value))
#[[1]]
#[1] 1 3 4 2
#[[2]]
#[1] 3 4 1 2
Or without anonymous function
lapply(y, match, df$value)
df <- data.frame(value = c(5, 25, 6, 70))
y <- list(c(5, 6, 70, 25), c(6, 70, 5, 25))
Upvotes: 2