根据指定所需顺序的目标向量订购数据帧行 [英] Order data frame rows according to a target vector that specifies the desired order

查看:104
本文介绍了根据指定所需顺序的目标向量订购数据帧行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更简单的方法来确保数据框的行按照目标向量排序,就像我在下面的简短示例中实现的一样?

Is there an easier way to ensure that a data frame's rows are ordered according to a "target" vector as the one I implemented in the short example below?

df <- data.frame(name = letters[1:4], value = c(rep(TRUE, 2), rep(FALSE, 2)))

df
#   name value
# 1    a  TRUE
# 2    b  TRUE
# 3    c FALSE
# 4    d FALSE

target <- c("b", "c", "a", "d")

这似乎有点太复杂了,以完成工作:

This somehow seems to be a bit too "complicated" to get the job done:

idx <- sapply(target, function(x) {
    which(df$name == x)
})
df <- df[idx,]
rownames(df) <- NULL

df 
#   name value
# 1    b  TRUE
# 2    c FALSE
# 3    a  TRUE
# 4    d FALSE


推荐答案

尝试 match

df <- data.frame(name=letters[1:4], value=c(rep(TRUE, 2), rep(FALSE, 2)))
target <- c("b", "c", "a", "d")
df[match(target, df$name),]

  name value
2    b  TRUE
3    c FALSE
1    a  TRUE
4    d FALSE

只要您的目标包含与 df $ name 完全相同的元素,它将工作,并且不包含重复的值。

It will work as long as your target contains exactly the same elements as df$name, and neither contain duplicate values.

匹配

match returns a vector of the positions of (first) matches of its first argument 
in its second.

因此 match 找到匹配的行号 target 的元素,然后按照该顺序返回 df

Therefore match finds the row numbers that matches target's elements, and then we return df in that order.

这篇关于根据指定所需顺序的目标向量订购数据帧行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆