根据向量以特定顺序对数据帧行进行排序 [英] Order data frame rows according to vector with specific order

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

问题描述

是否有一种更简单的方法来确保数据帧的行按照我在下面的简短示例中实现的那样根据目标"向量进行排序?

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

只要您的target包含与df$name完全相同的元素,并且都不包含重复的值,它将起作用.

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

来自?match:

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天全站免登陆