使用grepl为数据帧创建函数

使用grepl为数据帧创建函数,r,R,我有如下数据: A B 1 unicorn in the field 2 dog house in the yard 3 frog in the lake 4 house in the city 如果b有单词“House”或“Dog House”,我将尝试使用该数据创建一个新的数据框。我试过了 dogdata<-which(df$B == grepl('house|dog hou

我有如下数据:

A            B
1            unicorn in the field
2            dog house in the yard
3            frog in the lake
4            house in the city
如果b有单词“House”或“Dog House”,我将尝试使用该数据创建一个新的数据框。我试过了

dogdata<-which(df$B == grepl('house|dog house',df$B,ignore.case = TRUE)),A

但我总是出错。谢谢

您的子集表示法有点不正确,实际上您根本不需要
这一点

df[grepl('house|dog house', df$B, ignore.case = TRUE),]
grepl
返回一个真/假向量,我们可以用它来子集

另外,要反转您的选择(即选择不包含“house”或“dog house”的行),您必须使用
而不是
-

df[!grepl('house|dog house', df$B, ignore.case = TRUE),]

怎么样
df[which(grepl('house | dog house',df$B,ignore.case=TRUE)),]
哇!这很有效。太简单了!我就知道我很接近了。非常感谢!如果你回答这个问题,我会记下来的correct@Reagan没问题,而且我刚刚拔出了
,因为你不需要它。
df[!grepl('house|dog house', df$B, ignore.case = TRUE),]