我有大约 250 列的数据。示例如下所示:
如果他们在任何列中得分为“999”,我想删除行(代表参与者),因为这代表不正确的响应。我尝试了下面的一些简单代码,但这不起作用。
data %>%
filter_all(!= 999)
只有第 67 到 167 列才可能得到 999 分,但我认为在代码中跨数据的所有列指定会更容易。
有没有更好的方法?
最佳答案
我们可以使用if_all
library(dplyr)
data %>%
filter(if_all(everything(), ~ . != 999))
# shop1_freq shop1_enj shop2_freq shop2_enj
#1 0 9 3 6
#2 4 1 3 4
或者使用if_any
检查任意列中是否有“999”并取反(!
)
data %>%
filter(!if_any(everything(), ~ . == 999))
或者使用OP的方法(有点不推荐)
data %>%
filter_all(all_vars(.!= 999))
# shop1_freq shop1_enj shop2_freq shop2_enj
#1 0 9 3 6
#2 4 1 3 4
或者使用base R
和rowSums
来构建逻辑向量
data[rowSums(data == 999) == 0,]
或者将 999
替换为 NA 并使用 na.omit
na.omit(replace(data, data == 999, NA))
数据
data <- structure(list(shop1_freq = c(0L, 999L, 3L, 4L), shop1_enj = c(9L,
9L, 2L, 1L), shop2_freq = c(3L, 2L, 999L, 3L), shop2_enj = c(6L,
1L, 2L, 4L)), class = "data.frame", row.names = c(NA, -4L))
关于r - 在 R 中过滤掉多列中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66735932/