假设我有以下数据框:
User.Id Tags
34234 imageUploaded,people.jpg,more,comma,separated,stuff
34234 imageUploaded
12345 people.jpg
Run Code Online (Sandbox Code Playgroud)
我如何使用grep(或其他工具)来获取包含"imageUploaded"和"people"的行?换句话说,我怎么能创建一个只包含字符串"imageUploaded"和"people.jpg"的行的子集,而不管顺序如何.
我试过了:
data.people<-data[grep("imageUploaded|people.jpg",results$Tags),]
data.people<-data[grep("imageUploaded?=people.jpg",results$Tags),]
Run Code Online (Sandbox Code Playgroud)
有AND运算符吗?或者也许是另一种获得预期结果的方法?
Cha*_*ase 20
由于这个答案,这个正则表达似乎工作.您希望使用grepl()哪个返回逻辑索引到您的数据对象.我不会声称完全理解正则表达式的内部运作,但无论如何:
x <- c("imageUploaded,people.jpg,more,comma,separated,stuff", "imageUploaded", "people.jpg")
grepl("(?=.*imageUploaded)(?=.*people\\.jpg)", x, perl = TRUE)
#-----
[1] TRUE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)
Jos*_*ien 12
我喜欢@Chase的答案,这对我来说很有意义,但是使用一个人们并不完全理解的结构会有点危险.
这个答案是为了让任何想要使用@thelatemail更直接的方法的人放心,它的工作原理同样适用,并且速度完全具有竞争力.这肯定是我在这种情况下使用的.(同样令人放心的是,更复杂的Perl兼容正则表达式不会为其功能和易扩展性而付出任何性能成本.)
library(rbenchmark)
x <- paste0(sample(letters, 1e6, replace=T), ## A longer vector of
sample(letters, 1e6, replace=T)) ## possible matches
## Both methods give identical results
tlm <- grepl("a", x, fixed=TRUE) & grepl("b", x, fixed=TRUE)
pat <- "(?=.*a)(?=.*b)"
Chase <- grepl(pat, x, perl=TRUE)
identical(tlm, Chase)
# [1] TRUE
## Both methods are similarly fast
benchmark(
tlm = grepl("a", x, fixed=TRUE) & grepl("b", x, fixed=TRUE),
Chase = grepl(pat, x, perl=TRUE))
# test replications elapsed relative user.self sys.self
# 2 Chase 100 9.89 1.105 9.80 0.10
# 1 thelatemail 100 8.95 1.000 8.47 0.48
Run Code Online (Sandbox Code Playgroud)
为了便于阅读,您可以这样做:
x <- c(
"imageUploaded,people.jpg,more,comma,separated,stuff",
"imageUploaded",
"people.jpg"
)
xmatches <- intersect(
grep("imageUploaded",x,fixed=TRUE),
grep("people.jpg",x,fixed=TRUE)
)
x[xmatches]
[1] "imageUploaded,people.jpg,more,comma,separated,stuff"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19678 次 |
| 最近记录: |