简体   繁体   English

R中满足一定条件则省略分组

[英]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.

相关问题 R中满足一定条件的列组合 - Combinations of columns that meet a certain condition in R 在 R 中,有条件地计算在某个属性上满足 ANY 条件的 ID - In R, conditionally count IDs who meet an ANY condition on a certain attribute 如何在R中满足特定条件时获得连续出现的平均值 - How to get the average of consecutive occurrences when meet certain condition in R 如何使用 dplyr 在满足特定条件的 R 中保持组 - How to get keep groups in R which meet a certain conditions using dplyr 如何仅合并 r 中两个数据帧中满足特定条件的行 - How to merge only rows which meet a certain condition in two dataframes in r R:如果值满足特定条件,如何将数据框转换为邻接矩阵? - R: How do I transform a data frame into an adjacency matrix if values meet a certain condition? 如何将行除以行总和和矩阵中满足特定条件(行总和&gt; 100)的行? - How do I divide rows by the row sum and rows that meet a certain condition (row Sum >100)in matrix?r 对满足特定条件的所有行进行分组 - Group all rows that meet a certain condition 如果满足 R 中的条件,则 Append 或将文本添加到列 - Append or add text to a column if meet condition in R R-满足条件,然后继续循环,否则重复 - R - meet the condition then continue loop, otherwise repeat
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM