保留 select 列并根据字符串过滤其余列
Retain select columns and filter the rest based on string
我有一个数据集,我想在其中按特定字符串过滤掉,但除了过滤的列之外还保留两列。
例如
help <- data.frame(
data = c(type, 100, 100, 110, 110, 110),
user1 = c("red", "yes", "no", "yes", "no", "yes"),
user2 = c("blue", "yes", "no", "yes", "no", "yes"),
user3 = c("red", "yes", "no", "yes", "no", "yes"),
user4 = c("blue", "yes", "no", "yes", "no", "yes"),
more_data = c(5, 3, 6, 3, 4, 3))
我希望过滤掉数据第一行颜色为“红色”的用户,但同时保留 data
和 more_data
。
例如,我的最终数据集如下所示:
data user1 user3 more_data
1 type red red 5
2 100 yes yes 3
3 100 no no 6
4 110 yes yes 3
5 110 no no 4
6 110 yes yes 3
这是某种过滤器 + grepl 命令,我在其中过滤蓝色的反面吗? filter(help, grepl(!"blue", help))
但这不起作用。
我们可以使用 select
和 where
来检查 any
'red' 值或在 first
元素中
library(dplyr)
help %>%
select(data, where(~ 'red' %in% first(.)), more_data)
-输出
# data user1 user3 more_data
#1 type red red 5
#2 100 yes yes 3
#3 100 no no 6
#4 110 yes yes 3
#5 110 no no 4
#6 110 yes yes 3
数据
help <- structure(list(data = c("type", "100", "100", "110", "110", "110"
), user1 = c("red", "yes", "no", "yes", "no", "yes"), user2 = c("blue",
"yes", "no", "yes", "no", "yes"), user3 = c("red", "yes", "no",
"yes", "no", "yes"), user4 = c("blue", "yes", "no", "yes", "no",
"yes"), more_data = c(5, 3, 6, 3, 4, 3)), class = "data.frame",
row.names = c(NA,
-6L))
我有一个数据集,我想在其中按特定字符串过滤掉,但除了过滤的列之外还保留两列。
例如
help <- data.frame(
data = c(type, 100, 100, 110, 110, 110),
user1 = c("red", "yes", "no", "yes", "no", "yes"),
user2 = c("blue", "yes", "no", "yes", "no", "yes"),
user3 = c("red", "yes", "no", "yes", "no", "yes"),
user4 = c("blue", "yes", "no", "yes", "no", "yes"),
more_data = c(5, 3, 6, 3, 4, 3))
我希望过滤掉数据第一行颜色为“红色”的用户,但同时保留 data
和 more_data
。
例如,我的最终数据集如下所示:
data user1 user3 more_data
1 type red red 5
2 100 yes yes 3
3 100 no no 6
4 110 yes yes 3
5 110 no no 4
6 110 yes yes 3
这是某种过滤器 + grepl 命令,我在其中过滤蓝色的反面吗? filter(help, grepl(!"blue", help))
但这不起作用。
我们可以使用 select
和 where
来检查 any
'red' 值或在 first
元素中
library(dplyr)
help %>%
select(data, where(~ 'red' %in% first(.)), more_data)
-输出
# data user1 user3 more_data
#1 type red red 5
#2 100 yes yes 3
#3 100 no no 6
#4 110 yes yes 3
#5 110 no no 4
#6 110 yes yes 3
数据
help <- structure(list(data = c("type", "100", "100", "110", "110", "110"
), user1 = c("red", "yes", "no", "yes", "no", "yes"), user2 = c("blue",
"yes", "no", "yes", "no", "yes"), user3 = c("red", "yes", "no",
"yes", "no", "yes"), user4 = c("blue", "yes", "no", "yes", "no",
"yes"), more_data = c(5, 3, 6, 3, 4, 3)), class = "data.frame",
row.names = c(NA,
-6L))