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

bah*_*kev 10 grep parsing r

我希望做一些看似非常简单的事情.我想在几个不同的短语中使用grepl()命令(或类似的东西)在R中对数据帧进行子集化,而不构造循环.

例如,我想为名为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),]
Run Code Online (Sandbox Code Playgroud)

任何想法都会有所帮助!

Jus*_*tin 27

您可以将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
Run Code Online (Sandbox Code Playgroud)

  • @Justin这里`|`,不是一个逻辑或者,但是regexp替代运算符(即`paste(mynames,collapse ="&")`不会做你想象的那样) (4认同)