Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ^ with a variable

Tags:

r

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(^

like image 862
usr0192 Avatar asked Mar 12 '23 07:03

usr0192


1 Answers

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
like image 183
Gregor Thomas Avatar answered Mar 31 '23 01:03

Gregor Thomas