user90219 user90219 - 3 months ago 5
R Question

Using ^ with a variable

I know that using

grep
in R, if you want to find a certain string at the beginning, you use
^
, but how do I use it with a variable?

txt <- c("the cat ate the bill", "bill was late")


then

grep("^bill", txt)


returns
2
.

I want to write a function that takes a variable word
x
as input and finds if a line in
txt
begins with that word.
My first attempt is:

extract_word<-function(x){
grep(^x, txt)
}


but I get an error:


error unexpected ^ in:
"extract_word<-function(x, txt){
grep(^

Answer

The pattern argument to grep is just a string. If you want your pattern string to be the value of x with a ^ in front of it, then just create that string. paste0 is handy for sticking strings together with no spaces:

grep(paste0("^", x), txt)

Using your example:

txt <- c("the cat ate the bill", "bill was late")

x = 'bill'
grep(paste0("^", x), txt)
# [1] 2