【问题标题】:Multiple aggregation with unspecified FUN in RR中具有未指定FUN的多重聚合
【发布时间】:2020-06-08 04:18:33
【问题描述】:

我在 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

【问题讨论】:

标签: r dataframe group-by aggregation


【解决方案1】:

您可以尝试以下基本 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

【讨论】:

  • 谢谢,没猜到:)
猜你喜欢
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多