首页 > 解决方案 > R中具有未指定FUN的多重聚合

问题描述

我在 R 中有一个 data.frame 对象,需要:

  1. 按 col_1 分组
  2. 从 col_3 中选择行,使得 col_2 值是第二大的(如果只有 col_1 的给定值的观察值,例如返回“NA”)。

我怎样才能得到这个?

例子:

scored      xg  first_goal scored_mane

1       1 1.03212     Lallana           0

2       1 2.06000        Mane           1

3       2 2.38824   Robertson           1

4       2 1.64291        Mane           1 

"scored_mane"分组,从"scored"返回值,其中"xg"是第二大的。预期输出:“NA”,1

标签: rdataframegroup-byaggregation

解决方案


您可以尝试以下基本 R 解决方案,使用aggregate+merge

res <- merge(aggregate(xg~scored_mane,df,function(v) sort(v,decreasing = T)[2]),df,all.x = TRUE)[,"scored"]

这样

> res
[1] NA  1

数据

structure(list(scored = c(1L, 1L, 2L, 2L), xg = c(1.03212, 2.06, 
2.38824, 1.64291), first_goal = c("Lallana", "Mane", "Robertson", 
"Mane"), scored_mane = c(0L, 1L, 1L, 1L)), class = "data.frame", row.names = c("1", 
"2", "3", "4")) -> df

推荐阅读