简体   繁体   中英

Select rows conditional on value of a column in specific order

I have a dataframe, for example like this:

df <- data.frame(ID=c(8, 2, 5, 1, 4), value=c("a", "b", "c", "d", "e"))

  ID value
1  8     a
2  2     b
3  5     c
4  1     d
5  4     e

I know how to select rows with a given value in the "ID" column. But how to get rows conditional on their "ID"-values in a specified order?

Example: How to extract "value" for rows with ID 4, 2 and 5 in the given order? The result I want to get is "e", "b", "c".

Using %in% gives me the results in wrong order:

df[df$ID %in% c(4, 2, 5), "value"]

[1] b c e
Levels: a b c d e

I found a workaround using rownames, but I feel like there must be a better solution to this.

# workaround
rownames(df) <- df$ID
df[as.character(c(4, 2, 5)), "value"]

[1] e b c
Levels: a b c d e

Any suggestions?

Thank you!

You can use merge and order by a new introduced rank column :

dat = merge(df,data.frame(ID=c(4,2,5),v=1:3))
dat[order(dat$v),"value"]
[1] e b c

Or one linear option:

with(merge(df,data.frame(ID=c(4,2,5),v=1:3)),value[order(v)])
sapply(c(4,2,5), function(x) df[df$ID==x,"value"])

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