r - R中具有未指定FUN的多重聚合
问题描述
我在 R 中有一个 data.frame 对象,需要:
- 按 col_1 分组
- 从 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 解决方案,使用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
推荐阅读
- rust - 以编程方式在 Rust 上创建字符串切片
- node.js - MSSQL Nodejs Streaming 不等待完成返回
- c++ - 从模块中导出概念
- flutter - 如何使用动态参数名称调用实例方法?
- ios - Swift 将项目重构为 MVVM-C
- environment-variables - 环境变量不适用于 NextJS 上的 Mapbox 令牌
- json - neo4j 使用 apoc 加载 1000 个 json 文档
- python - 我应该如何在 Django Rest Framework API 中返回用户名而不是 id?
- java - 更新数据库并以相同的方法调用存储过程,但似乎不在同一个会话中
- android - 请像我 5 岁一样解释:Flutter 中 MainAxisSize 的目的是什么?