Ami*_*tai 3 sorting r data.table
如何找到每列的前k(比如k = 3)值的索引
> dt <- data.table( x = c(1, 1, 3, 1, 3, 1, 1), y = c(1, 2, 1, 2, 2, 1, 1) )
> dt
x y
1: 1 1
2: 1 2
3: 3 1
4: 1 2
5: 3 2
6: 1 1
7: 1 1
Run Code Online (Sandbox Code Playgroud)
所需输出:
> output.1
x y
1: 1 2
2: 3 4
3: 5 5
Run Code Online (Sandbox Code Playgroud)
或者甚至更好(注意x中额外有用的降序排序):
> output.2
var top1 top2 top3
1: x 3 5 1
2: y 2 4 5
Run Code Online (Sandbox Code Playgroud)
拥有输出将是一个很大的帮助.
在循环遍历数据集的列之后,我们可以使用sort(with index.return=TRUE)lapply
dt[, lapply(.SD, function(x) sort(head(sort(x,
decreasing=TRUE, index.return=TRUE)$ix,3)))]
# x y
#1: 1 2
#2: 3 4
#3: 5 5
Run Code Online (Sandbox Code Playgroud)
或者使用 order
dt[, lapply(.SD, function(x) sort(head(order(-x),3)))]
Run Code Online (Sandbox Code Playgroud)