Using ^ with a variable

I know that using grepin R, if you want to find a specific line at the beginning, you use ^, but how can 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 enters a variable word xas input and finds if the string in txtbegins with that word. My first attempt:

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

but I get an error:

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

+4
source share
1 answer

pattern grep - . , x ^ , . paste0 :

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

:

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

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

Source: https://habr.com/ru/post/1652536/


All Articles