首页 > 解决方案 > 如何在 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

如果有人可以提供帮助,将不胜感激?

标签: r

解决方案


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

推荐阅读