Can I gracefully include formatted SQL strings in an R script?

前端 未结 5 1586
清歌不尽
清歌不尽 2020-12-14 04:55

I\'m working in an R script that uses a long SQL string, and I would like to keep the query relatively free of other markup so as to allow copying and pasting between editor

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 05:35

    A graceful way of "including" a long SQL query is to keep it in a separate .sql file. Preferably somewhere it can be syntax highlighted, a text file in RStudio will do the job. You can then in your main R script read the file into a string and populate it with variables using one of the many "named" sprintf-type solutions, such as infuser.

    .sql

    select *
    from mytable
    where id = {{a}} 
    and somevar = {{b}}
    

    .R

    library(readr)
    library(infuser)
    
    query <- read_file("query.sql") %>%
             infuse(a = 1, b = 2) 
    

提交回复
热议问题