[英]Subset based on list of strings using grepl()?
我正在做一些看似非常簡單的事情。 我想使用 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),]
任何想法都會有所幫助!
您可以將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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.