简体   繁体   中英

How do I get the index of all elements in a list, according to data given in a data.frame in R?

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

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)

data

df <- data.frame(value = c(5, 25, 6, 70))
y <- list(c(5, 6, 70, 25), c(6, 70, 5, 25))

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"])

Note

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM