根据数据框(R)的ANY列中的值删除行

时间:2019-12-04 14:28:53

标签: r

我有与发布的问题相同的问题,例如这里: Delete row based on value in any column of the dataframe 但希望使用R中的解决方案。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

一个选项是filter_at中的dplyr

library(dplyr)
df1 %>%
    filter_at(vars(col1, col2),  all_vars(!str_detect(., "December 31,$")))
#               col1 col2 col3
#1 December 31, 2019   21   22
#2          countryB   19   23
#3          countryC   18   14

或者在base R中与Reducegrep

df1[!Reduce(`|`, lapply(df1[c('col1', 'col2')], grepl,
          pattern = "December 31,$")),]
#               col1 col2 col3
#2 December 31, 2019   21   22
#3          countryB   19   23
#4          countryC   18   14

数据

df1 <- structure(list(col1 = c("December 31,", "December 31, 2019", 
"countryB", "countryC"), col2 = c("December 31,", "21", "19", 
"18"), col3 = c(NA, 22, 23, 14)), class = "data.frame", row.names = c(NA, 
-4L))