r - 如何在 R 的另一列中选择最多一列而不是 NA?
问题描述
我在 R 中寻找一种方法,我可以选择其中 col2 不是 NA 的 max(col1)?
名为 df1 的示例数据名
#df1
Year col1 col2
2016 4 NA # has NA
2016 2 NA # has NA
2016 1 3 # this is the max for 2016
2017 3 NA
2017 2 3 # this is the max for 2017
2017 1 3
2018 2 4 # this is the max for 2018
2018 1 NA
我希望新数据集只返回
Year col1 col2
2016 1 3
2017 2 3
2018 2 4
如果有人可以提供帮助,将不胜感激?
解决方案
在base R
out <- na.omit(df1)
merge(aggregate(col1 ~ Year, out, max), out) # thanks to Rui
# Year col1 col2
#1 2016 1 3
#2 2017 2 3
#3 2018 2 4
推荐阅读
- regex - 如何删除 Trino 中的非英文字符
- git - 应用 git stash 时如何忽略空格?
- flutter - 使用颤振提供程序包验证表单的最佳方法?
- filter - 计算每个 ID 的 2 个最小日期之间的差异
- c++ - 传递可变大小的多维数组
- terraform - 如何创建 `.terraform/providers/linux_amd64/lock.json` 文件?
- swagger - 使用 ref 参数时如何指定所需的属性?
- java - 使用 JAVA 修改 LDAP 中的用户属性
- owasp - OWASP CRS MoD 安全误报 - 规则 942150 “@contains”
- python - 使用 selenium 的点击音频挑战 recaptcha v2 的问题