[英]How to subset a data frame based on categorical variables when a row can be defined by more than categorical variable
我有一個非常大的數據框,我想刪除包含某些分類變量的所有條目。 數據框是這樣的,一個行條目可以有多個分配給它的分類變量。 在這個簡化的例子中:
x<-(1:10)
y<-c("a,b","c,d","c","c","a","a,d","b,d","c","c","a")
example_df <- data.frame(x,y)
example_df
請注意,行條目 1 被定義為由逗號分隔的“a”和“b”,而第 5 行被定義為“a”。 例如,如何命令 R 返回一個新數據框,該數據框僅包含不包含列“y”的“a”的行?
使用 dplyr 和 stringr
library(dplyr)
library(stringr)
example_df %>% filter(!str_detect(y,'a'))
x y
1 2 c,d
2 3 c
3 4 c
4 7 b,d
5 8 c
6 9 c
您可以使用grepl
進行模式匹配並返回其中沒有 'a' 的行。
subset(example_df, !grepl('a', y))
# x y
#2 2 c,d
#3 3 c
#4 4 c
#7 7 b,d
#8 8 c
#9 9 c
我們也可以做
subset(example_df, setdiff(seq_len(nrow(example_df)), grep('a', y)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.