user90219 user90219 -4 years ago 89
R Question

Using ^ with a variable

I know that using

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")


grep("^bill", txt)


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

grep(^x, txt)

but I get an error:

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

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download