如何删除包含特定值的所有行,而不管它在哪个列中

时间:2017-04-27 20:37:53

标签: r subset apply

我需要删除包含值2或-2的所有行,而不管它除了第一列之外的列。

示例数据框:

DF

  a    b    c    d
zzz    2    2   -1
yyy    1    1    1
xxx    1   -1   -2

期望的输出:

DF

  a    b    c    d
yyy    1    1    1

我试过了

df <- df[!grepl(-2 | 2, df),]

df <- subset(df, !df[-1] == 2 |!df[-1] == -2)

我的实际数据集有超过300行和70个变量

我相信我需要使用某种apply功能,但我不确定。

如果您需要更多信息,请与我们联系。

2 个答案:

答案 0 :(得分:2)

我们可以通过比较数据集的绝对值和2的绝对值来创建逻辑索引,得到行方式和,如果没有值,它将为0(通过否定!,它返回TRUE对于那些0值而对于其他值为FALSE)和基于逻辑索引的子集

df[!rowSums(abs(df[-1])==2),]
#   a b c d
#2 yyy 1 1 1

或者另一种选择是使用lapply在每列中进行比较,将其折叠为具有|的逻辑向量,并使用它来对行进行子集

df[!Reduce(`|`,lapply(abs(df[-1]), `==`, 2)),]
#    a b c d
#2 yyy 1 1 1

我们也可以使用tidyverse

执行此操作
library(tidyverse)
df %>% 
    select(-1) %>% #to remove the first column
    map(~abs(.) ==2) %>% #do the columnwise comparison
    reduce(`|`) %>% #reduce it to logical vector
    `!` %>%  #negate to convert TRUE/FALSE to FALSE/TRUE
     df[., ] #subset the rows of original dataset
#     a b c d
# 2 yyy 1 1 1

数据

df <- structure(list(a = c("zzz", "yyy", "xxx"), b = c(2L, 1L, 1L), 
c = c(2L, 1L, -1L), d = c(-1L, 1L, -2L)), .Names = c("a", 
"b", "c", "d"), class = "data.frame", row.names = c(NA, -3L))

答案 1 :(得分:0)

dplyr的选项:

library(dplyr)
a <- c("zzz","yyy","xxx")
b <- c(2,1,1)
c <- c(2,1,-1)
d <- c(-1,1,-2)

df <- data.frame(a,b,c,d)

filter(df,((abs(b) != 2) & (abs(c) != 2) & (abs(d) != 2)))

    a b c d
1 yyy 1 1 1