Create Influx query as a function in R

Viewed 39

I am trying to turn the Influx query into a function in R so I can change the fields as I see fit. Here is an example of the code I am running

my_bucket <- "my_bucket"
start <- "start_time"
stop <- "stop_time"
q <- paste('from(bucket:',my_bucket,')|> range(start:',start,'stop:,'stop')',sep = "")
data <- client$query(q)

Error in private$.throwIfNot2xx(resp) : 
  API client error (400): compilation failed: error at @1:1-1:2: invalid statement: '

This particular method uses paste() and it keeps the escape character \ in the query. I would like to get rid of that . I have tried using cat() but that is for printing to the console and also have tried capture.output() of the cat() string which still captures the escape characters.

What I would like to see and be stored as an object is the output below. I used cat() to show you exactly what I need (I know I can't use it to store things).

cat('\'from(bucket:\"',my_bucket,'\")|> range(start:',start,',stop:,',stop,')\'', sep = "")
>'from(bucket:"my_bucket")|> range(start:start_time,stop:,stop_time)'

Note the single quotes around the query beginning at from and ending after the parantheses after stop_time. In addtion the double quotes must be present around the bucket I call to. This is required syntax for the query from R.

1 Answers

I would suggest you try to use sprintf, I find it much easier to properly format the query.

q <- sprintf('from(bucket: "%s") |> range(start: %s, stop: %s)', my_bucket, start, stop)

Anyway, the same can be done with paste:

q <- paste('from(bucket: "',my_bucket,'") |> range(start: ',start,',stop: ',stop,')',sep = "")
Related