我知道grep
在R中使用,如果您想在开始时找到某个字符串,可以使用^
,但是如何将它与变量一起使用?
txt <- c("the cat ate the bill", "bill was late")
然后
grep("^bill", txt)
返回2
。
我想编写一个函数,该函数将可变单词x
作为输入,并查找一行是否txt
以该单词开头。我的第一次尝试是:
extract_word<-function(x){
grep(^x, txt)
}
但我得到一个错误:
错误意外的^ in:“ extract_word <-function(x,txt){grep(^
的pattern
参数grep
只是一个字符串。如果想让模式字符串成为其前面x
带有a的值^
,则只需创建该字符串即可。paste0
对于不带空格的字符串粘贴非常方便:
grep(paste0("^", x), txt)
使用您的示例:
txt <- c("the cat ate the bill", "bill was late")
x = 'bill'
grep(paste0("^", x), txt)
# [1] 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句