简体   繁体   English

R 如果三个或更多值为 NA,则删除行

[英]R Removing row if three or more values are NA

I feel like I should be able to do this with filter or subset, but can't figure out how.我觉得我应该能够使用过滤器或子集来做到这一点,但不知道如何。

How do I remove a row if three or more of the cells in that row are "NA"?如果该行中的三个或更多单元格为“NA”,如何删除该行?

So in this dataset, rows with titles 1A-C2 and 3A-C2 would be removed.所以在这个数据集中,标题为 1A-C2 和 3A-C2 的行将被删除。

my_data <- data.frame(Title = c("1A-C2", "1D-T2", "1F-T1", "1E-C2", "3A-C2", "3F-T2"),
                      Group1 = c(NA, 10, 2, 9, NA, 4), Group2 = c(1, 3, 6, 1, NA, 3), Group3=c(NA, 3, 3, 8, NA, 4), Group4=c(NA, NA, 4, 5, 1, 7), Group5=c(1, 4, 3, 3, 9, NA), Group6=c(NA, 4, 5, 6, 1, NA))

Thank you!!谢谢!!

With Base R ,Base R ,

  my_data[rowSums(is.na(my_data))<3,]

gives,给,

  Title Group1 Group2 Group3 Group4 Group5 Group6
2 1D-T2     10      3      3     NA      4      4
3 1F-T1      2      6      3      4      3      5
4 1E-C2      9      1      8      5      3      6
6 3F-T2      4      3      4      7     NA     NA

Using dplyr :使用dplyr

library(dplyr)

my_data %>%
  rowwise() %>%
  filter(sum(is.na(c_across(starts_with('Group')))) < 3)

#  Title Group1 Group2 Group3 Group4 Group5 Group6
#  <chr>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
#1 1D-T2     10      3      3     NA      4      4
#2 1F-T1      2      6      3      4      3      5
#3 1E-C2      9      1      8      5      3      6
#4 3F-T2      4      3      4      7     NA     NA

In base R , we can use Reduce with is.nabase R中,我们可以将Reduceis.na一起使用

subset(my_data, Reduce(`+`, lapply(my_data[startsWith(names(my_data), "Group")],
       is.na)) < 3)
#  Title Group1 Group2 Group3 Group4 Group5 Group6
#2 1D-T2     10      3      3     NA      4      4
#3 1F-T1      2      6      3      4      3      5
#4 1E-C2      9      1      8      5      3      6
#6 3F-T2      4      3      4      7     NA     NA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM