gpt4 book ai didi

r - 如何获取 data.table 中每个(选定)列的前 k 值的索引

转载 作者:行者123 更新时间:2023-12-01 08:26:03 25 4
gpt4 key购买 nike

如何查找每列的前 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

需要的输出:

> output.1
x y
1: 1 2
2: 3 4
3: 5 5

甚至更好(注意 x 中额外有用的降序排序):

> output.2
var top1 top2 top3
1: x 3 5 1
2: y 2 4 5

拥有输出已经是一个很大的帮助。

最佳答案

我们可以在使用 lapply

遍历数据集的列之后使用 sort(使用 index.return=TRUE)
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

或者使用order

dt[, lapply(.SD, function(x) sort(head(order(-x),3)))]

关于r - 如何获取 data.table 中每个(选定)列的前 k 值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34908506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com