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(^
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With