如果任何列包含特定字符串,则删除行

时间:2017-06-14 12:17:39

标签: r

我正在尝试找出R中删除包含特定字符串的行的最佳方法,在我的情况下' no_data'。

我有来自外部来源的数据,这些数据用“no_data”'

来判断na

一个例子是:

IntroView.vue

我想浏览数据并删除包含此内容的每一行' no_data'任何列中的字符串。我很难搞清楚这一点。我尝试了一个sapply,filter,grep以及三者的组合。我绝不是一个专家,所以它可能只是我错误地使用这些。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:8)

我们可以使用rowSums创建逻辑vector和基于它的子集

df1[rowSums(df1 == "no_data")==0, , drop = FALSE]
#   time speed wheels
#4 3:00    50     18

数据

df1 <- structure(list(time = c("1:00", "2:00", "no_data", "3:00"), speed = c("30", 
"no_data", "no_data", "50"), wheels = c("no_data", "18", "no_data", 
"18")), .Names = c("time", "speed", "wheels"), class = "data.frame", 
row.names = c(NA, -4L))

答案 1 :(得分:7)

您可以使用na.strings = 'no_data'阅读数据,将其设置为NA,然后只需省略NAs(或采用complete.cases),即(使用@ akrun的数据集)

d1 <- read.table(text = 'time   speed  wheels
 1    1:00      30 no_data
            2    2:00 no_data      18
            3 no_data no_data no_data
            4    3:00      50      18', na.strings = 'no_data', h=TRUE)

d1[complete.cases(d1),]
#  time speed wheels
#4 3:00    50     18

#OR

na.omit(d1)
#  time speed wheels
#4 3:00    50     18

答案 2 :(得分:3)

选项:(使用@ Akrun的数据)

require(dplyr)
df1 %>% filter_all(all_vars(!grepl('no_data',.)))

 time speed wheels
1 3:00    50     18

警告:这只适用于&#34;否定选择&#34;。如果您想获取所有包含字符串的行,仅删除!是不够的,因为它只会选择所有列包含的行串。如果您想这样做,请改用filter_all(any_vars())

答案 3 :(得分:2)

akrun的答案是快速,正确的,并且尽可能多的:) 但是,如果你想让自己的生活更加复杂,你也可以这样做:

dat
     time   speed  wheels
1    1:00      30 no_data
2    2:00 no_data      18
3 no_data no_data no_data
4    3:00      50      18

dat$new <- apply(dat[,1:3], 1, function(x) any(x %in% c("no_data")))
dat <- dat[!(dat$new==TRUE),]
dat$new <- NULL

dat
  time speed wheels
4 3:00    50     18
相关问题