Miscellaneous snippets for future reference.


Writing to json

Using the jsonlite package.

library(jsonlite)

json_list <- list(arg1 = "random_arg_value1", arg2 = "random_arg_value2")
json_export <- toJSON(json_list, auto_unbox = TRUE)
write(json_export, "example.json")


Calling R script from batch file with parameters

The batch file.

set arg1=4
set arg2=experiment_02
"C:\Program Files\R\R-4.1.0\bin\Rscript.exe" C:\path\to\R\script\example_r_script.R %arg% %arg2% 

Retrieving arguments in the R script.

args <- commandArgs(trailingOnly = TRUE)

arg1 <- args[1]        
arg2 <- args[2]


Reading an sql file in R

read_sql <- function(file_path) {
  
  sql_text <- paste(readLines(file_path, warn = FALSE))      # Read entire file as one string
  sql_text <- gsub("--.*$", "", sql_text, perl = TRUE)       # Remove comments --
  sql_text <- gsub("[\r\n]+", " ", sql_text)                 # Collapse multiple spaces/newlines
  sql_text <- trimws(sql_text)                               # Trim whitespace
  sql_text <- paste(sql_text, collapse = " ")                # Collapse
  sql_text <- gsub("/\\*.*?\\*/", "", sql_text, perl = TRUE) # Remove comments /*...*/
  #sql_text <- sql_text[nzchar(sql_text)]
  
  return(sql_text)
}