[英]Omit groups if they meet a certain condition in R
My data are as follows:我的数据如下:
df <- structure(list(year = c(2019L, 2019L, 2019L, 2019L, 2020L, 2020L,
2020L, 2020L), site = c("A", "B", "C", "D", "A", "B", "C", "D"
), value = c(200L, 100L, 50L, NA, 300L, NA, NA, NA), dist = c(10L,
15L, 30L, 36L, 10L, 15L, 30L, 36L)), class = "data.frame", row.names = c(NA,
-8L))
I would like to omit an entire group (the year) if there is greater than one NA value within the group.如果组内有一个以上的 NA 值,我想省略整个组(年份)。
In the data example I provide, the outcome would be a dataframe with only 2019 observations (though my real data have many more years).在我提供的数据示例中,结果将是 dataframe,只有 2019 年的观测值(尽管我的真实数据有更多年)。
Thank you in advance!先感谢您!
Try:尝试:
library(dplyr)
df %>% group_by(year) %>% filter(sum(is.na(value))<2)
# year site value dist
# <int> <chr> <int> <int>
# 1 2019 A 200 10
# 2 2019 B 100 15
# 3 2019 C 50 30
# 4 2019 D NA 36
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.