基于使用grepl()的字符串列表的子集?

基于使用grepl()的字符串列表的子集?,r,parsing,grepl,R,Parsing,Grepl,我想做一些看起来很简单的事情。我想在R中使用grepl()命令或类似的命令将数据帧子集到几个不同的短语上,而不构建循环 例如,我想为名为Bob或Mary的任何人提取所有行: ## example data frame: tmp = structure(list(Name = structure(c(6L, 8L, 9L, 7L, 2L, 3L, 10L, 1L, 5L, 4L), .Label = c("Alan", "Bob", "bob smith", "Frank", "John",

我想做一些看起来很简单的事情。我想在R中使用grepl()命令或类似的命令将数据帧子集到几个不同的短语上,而不构建循环

例如,我想为名为Bob或Mary的任何人提取所有行:

## example data frame:
tmp = structure(list(Name = structure(c(6L, 8L, 9L, 7L, 2L, 3L, 10L, 
1L, 5L, 4L), .Label = c("Alan", "Bob", "bob smith", "Frank", 
"John", "Mary Anne", "mary jane", "Mary Smith", "Potter, Mary", 
"smith, BOB"), class = "factor"), Age = c(31L, 23L, 23L, 55L, 
32L, 36L, 45L, 12L, 43L, 46L), Height = 1:10), .Names = c("Name", 
"Age", "Height"), class = "data.frame", row.names = c(NA, -10L
))

tmp

#           Name Age Height
#1     Mary Anne  31      1
#2    Mary Smith  23      2
#3  Potter, Mary  23      3
#4     mary jane  55      4
#5           Bob  32      5
#6     bob smith  36      6
#7    smith, BOB  45      7
#8          Alan  12      8
#9          John  43      9
#10        Frank  46     10

## this doesn't work
mynames=c('bob','mary')
tmp[grepl(mynames,tmp$Name,ignore.case=T),]

任何想法都会有帮助

您可以将
mynames
向量与正则表达式运算符
|
组合使用
grep

tmp[grep(paste(mynames, collapse='|'), tmp$Name, ignore.case=TRUE),]

#           Name Age Height
# 1    Mary Anne  31      1
# 2   Mary Smith  23      2
# 3 Potter, Mary  23      3
# 4    mary jane  55      4
# 5          Bob  32      5
# 6    bob smith  36      6
# 7   smith, BOB  45      7

您应该会在控制台中收到警告,因为
grep
函数系列需要一个指定模式的字符串(固定字符串或正则表达式)。
?grep
中的文档说明,“如果提供了长度为2或更长的字符向量,则第一个元素将与警告一起使用。”@Justin here
|
不是逻辑or,但regexp替代运算符(即
粘贴(mynames,collapse=“&”)
不会执行您可能期望的操作)