根据具有特定顺序的向量对数据框行进行排序 [英] Order data frame rows according to vector with specific order
本文介绍了根据具有特定顺序的向量对数据框行进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更简单的方法来确保数据框的行根据目标"向量进行排序,就像我在下面的简短示例中实现的那样?
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
推荐答案
Try 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屋!
查看全文