目的是解析正则表达式并替换匹配的模式。
考虑这个例子:
data <- c("cat 6kg","cat g250", "cat dog","cat 10 kg")
我必须找到所有出现的cat
和数字[0-9]
。要做到这一点:
found <- data[grepl("(^cat.[a-z][0-9])|(^cat.[0-9])",data)]
found
[1] "cat 6kg" "cat g250" "cat 10 kg"
下一步是将found
的每个元素替换为字符串cat
。我已经尝试过gsub, sub和gsubfn()从包(gsubfn)根据堆栈问题20219311:
gsubfn("((^cat.[a-z][0-9])|(^cat.[0-9]))", "cat",data)
[1] "catkg" "cat50" "cat dog" "cat0 kg"
不是预期的结果:
[#] "cat" "cat" "cat dog" "cat"
我想我漏掉了一点。我将感激任何我能得到的帮助。谢谢。
简单,,,,只需将字符串cat
分配给匹配元素。这将用cat
> data <- c("cat 6kg","cat g250", "cat dog","cat 10 kg")
> data[grepl("(^cat.[a-z][0-9])|(^cat.[0-9])",data)] <- "cat"
> data
[1] "cat" "cat" "cat dog" "cat"
或
> data <- c("cat 6kg","cat g250", "cat dog","cat 10 kg")
> data[grepl("^cat.[a-z]?[0-9]",data)] <- "cat"
> data
[1] "cat" "cat" "cat dog" "cat"
你也可以做
sub('\s*dog(*SKIP)(*F)|(?<=cat).*', '', data, perl=TRUE)
#[1] "cat" "cat" "cat dog" "cat"
或
sub('(cat)\s*([0-9]|[a-z][0-9]).*$', '\1', data)
#[1] "cat" "cat" "cat dog" "cat"
试试这个:
gsub('(\w?[0-9].*)','',data)
#[1] "cat " "cat " "cat dog" "cat "