R data.table函数中的结果顺序错误
我发现,在data.table()内部,order函数按组枚举行,而最初的想法是查看指定组中每个观察值的排名 以下是一个可复制的示例:R data.table函数中的结果顺序错误,r,data.table,R,Data.table,我发现,在data.table()内部,order函数按组枚举行,而最初的想法是查看指定组中每个观察值的排名 以下是一个可复制的示例: require(data.table) N <- 10 set.seed(1) test <- data.table( a = round(rnorm(N,mean=0, sd = 30),0), b = c(rep('group_1', N/2 ),rep('group_2', N/2)) ) test <- test[, ite
require(data.table)
N <- 10
set.seed(1)
test <- data.table(
a = round(rnorm(N,mean=0, sd = 30),0),
b = c(rep('group_1', N/2 ),rep('group_2', N/2))
)
test <- test[, item_position := order(a, decreasing = T), by=list(b)]
setkey(test, b, item_position)
View(test)
这显然是错误的。
我做错了什么,如何在data.table中使用order()
谢谢大家! 我想你对
order
的功能有点误解。从你描述的每一件事来看,你实际上是在寻找rank
:
test[, B_S := rank(-a, ties.method="first"), by = b][] ## Big to Small
# a b B_S
# 1: -19 group_1 4
# 2: 6 group_1 3
# .. SNIP ..
# 9: 17 group_2 2
# 10: -9 group_2 4
test[, S_B := rank(a, ties.method="first"), by = b][] ## Small to big
# a b B_S S_B
# 1: -19 group_1 4 2
# 2: 6 group_1 3 3
# .. SNIP ..
# 9: 17 group_2 2 4
# 10: -9 group_2 4 2
setkey(test, b, S_B)
test
# a b B_S S_B
# 1: -25 group_1 5 1
# 2: -19 group_1 4 2
# 3: 6 group_1 3 3
# 4: 10 group_1 2 4
# 5: 48 group_1 1 5
# 6: -25 group_2 5 1
# 7: -9 group_2 4 2
# 8: 15 group_2 3 3
# 9: 17 group_2 2 4
# 10: 22 group_2 1 5
订单输出没有任何问题(除了它不是您所期望的)。考虑以下事项:
x <- c(-19, 6, -25, 48, 10)
order(x, decreasing=TRUE)
# [1] 4 5 2 1 3
cbind(x, order(x, decreasing=TRUE))
# x
# [1,] -19 4
# [2,] 6 5
# [3,] -25 2
# [4,] 48 1
# [5,] 10 3
xAnanda的解决方案是小型数据集的发展方向。对于较大的,当速度成为一个问题时,您可能需要使用数据。表的设置键:
test[, idx := .I] # save index to reorder later
setkey(test, b, a) # order the way we want
test[, pos := 1:.N, by = b] # save the positions per group
setkey(test, idx) # back to original order
我认为您实际上是在寻找排名
而不是顺序
。也许是这样的:test[,item_position:=rank(a,ties.method=“first”),by=b][
?@eddi,有趣的是他们确实使用了set.seed
,但我得到了完全不同的结果:-)@eddie抱歉,我的坏,修复了结果。这仍然不是我所期望的,但我希望这次它匹配:)@AnandaMahto+1,您的解决方案有效,但我仍然不明白order()为什么不能按我所期望的方式工作。您也可以直接使用内部快速排序函数(而不是诉诸setkey
),但我真的不知道什么时候使用这些函数
test[, idx := .I] # save index to reorder later
setkey(test, b, a) # order the way we want
test[, pos := 1:.N, by = b] # save the positions per group
setkey(test, idx) # back to original order