是否有 R 函数可以过滤变量中的任何字符串?

is there an R function to filter any string in a variable?

我有一个包含字符串和 NA 的数据。我想要一个 r 函数来过滤任何字符串和任何 NA。 我的数据看起来像这样

a<-c(1,2,3,4)
b<-c("james","NA",1,2)
c<-data.frame(a,b)
c

我需要这样的输出

a<-c(1,2)
b<-c("james","NA")
d<-data.frame(a,b)
d

您可以 select 没有所有数字的行。

subset(c, !grepl('^\d+$', b))

#  a     b
#1 1 james
#2 2    NA

这个也可以用在dplyr::filter-

dplyr::filter(c, !grepl('^\d+$', b))

请注意,在数据中,您有字符串 "NA" 而不是真正的 NA 值。但是,如果您有真实的 NA 值,即如果 b 向量是 b<-c("james",NA,1,2).

,则上述答案也有效

我们可以使用 grepnegate = TRUE

c[grep('^\d+$', c$b, negate = TRUE),]

str_detect

library(dplyr)
library(stringr)
c %>% 
    filter(str_detect(b, '^\d+$', negate = TRUE))
  a     b
1 1 james
2 2    NA