Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用data.table的嵌套分组中的前n名_R_Data.table_Top N - Fatal编程技术网

R 使用data.table的嵌套分组中的前n名

R 使用data.table的嵌套分组中的前n名,r,data.table,top-n,R,Data.table,Top N,目标:按季度和姓名分组我希望按计数获得前n名(见下面的示例)。因此,top 1(如下例)的期望输出为: 2019 Q1 Klaus 2 2019 Q2 Karl 3 由于这只是一个玩具的例子,我还想有前4,5等计数每季度和名称。 您对如何使用data.table(请不要使用dplyr)实现这一点有什么好主意吗。非常感谢 library(data.table) dt <- data.table(x = c("2019 Q1", "2019 Q1", "2019 Q1", "2019

目标:按季度和姓名分组我希望按计数获得前n名(见下面的示例)。因此,top 1(如下例)的期望输出为:

2019 Q1  Klaus 2
2019 Q2   Karl 3
由于这只是一个玩具的例子,我还想有前4,5等计数每季度和名称。 您对如何使用
data.table
(请不要使用
dplyr
)实现这一点有什么好主意吗。非常感谢

library(data.table)

dt <- data.table(x = c("2019 Q1", "2019 Q1", "2019 Q1", "2019 Q2", "2019 Q2", "2019 Q2", "2019 Q2"),
                 y = c("Klaus", "Gustav", "Klaus", "Karl", "Karl", "Karl", "Stefan"))

# Structure of dt
# x      y
# 1: 2019 Q1  Klaus
# 2: 2019 Q1 Gustav
# 3: 2019 Q1  Klaus
# 4: 2019 Q2   Karl
# 5: 2019 Q2   Karl
# 6: 2019 Q2   Karl
# 7: 2019 Q2 Stefan


dt[, .N, by = .(x, y)]

# Output:
# x      y N
# 1: 2019 Q1  Klaus 2
# 2: 2019 Q1 Gustav 1
# 3: 2019 Q2   Karl 3
# 4: 2019 Q2 Stefan 1
库(data.table)

dt您可以首先计算每个名称和季度的N,然后对data.table排序,然后选择每个季度的前N行:

dt[, .N, by = .(x, y)][order(-N), head(.SD, 1), by = x]

下面是一个使用聚合的基本R解决方案

> aggregate(y~x,dt,function(v) as.matrix(head(data.frame(sort(table(v),decreasing = TRUE)),1)))
        x   y.1 y.2
1 2019 Q1 Klaus   2
2 2019 Q2  Karl   3

这是另一种
data.table
方法,与Gilean的答案几乎相同,但没有
head()


另一个包含
数据的解决方案。表

dt[, .N, by = .(x, y)][, .SD[N==max(N)][1], x]
或者更好

dt[, .N, by = .(x, y)][, head(.SD[N==max(N)], 1), x]

@罗纳克沙姆:是的,会的……:)我添加
head()
的原因是,如果OP希望每个季度获得前4或前5个名称,那么如果每个季度没有那么多名称,此解决方案将使用
NAs
添加额外的行。@Gilean0709,我理解。我想这取决于OP的用例;-)很好的一个,没有想到当每个组中都没有(完全)存在一个顶层时,
head()
不会导致
NA
。。。将在我自己的工作中记住这一点;-)
dt[, .N, by = .(x, y)][, head(.SD[N==max(N)], 1), x]