'R: Recognizing a variable in a string query?

Hello stack overflow R community :)

I am trying to write a loop or alternatively a function that I can apply to a vector of values in a table that sends a query to a database. The exact details are possibly not too important as this is more of a general question. Given that the query is a string like this:

query <- '1456-2365 some more text'

the number in the beginning is a reference number which is the type of variable I am trying to 'loop' over. As in I have column with similar built values in my table and I'm trying to query all of them. My question is how do I make R recognize my variable within the string?

I have thought of using str_replace or similar before re-running the query, are there any better ways of doing this?



Solution 1:[1]

The details are important here. If your number is always at the start of the string and always followed by a space, you could do:

str_extract(df$query, '^\\H*')
#> [1] "1456-2365" "1326-1365" "4567-2885"

If your number is not always at the start, but always 4 digits followed by a dash and another four numbers, you could do:

str_extract(df$query, '\\d+-\\d+')
#> [1] "1456-2365" "1326-1365" "4567-2885"

Data

df <- data.frame(query = c('1456-2365 some more text',
                           '1326-1365 blah blah text',
                           '4567-2885 text blah blah'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allan Cameron