tags:

views:

74

answers:

3

Using R, I just want to read the contents of a file into a variable like:

query <- read_file_contents('biglongquery.sql')

As to avoid putting, well, big long queries in the R script itself. I do not want to read in data like CSV (e.g. read.tables), etc- just the raw text.

A: 
x <- paste(scan("foo.sql",what="",sep="\n",blank.lines.skip=FALSE),collapse="\n")
Joshua Ulrich
+2  A: 

Scan does the job, but the function for this purpose is actually readLines().

query <- readLines("biglongquery.sql")

This gives you a vector with the lines. To combine them to one single variable, you can use the paste function, e.g.

one.variable <- paste(query,collapse="\n")
Joris Meys
And if one use it a lot then `readQuery<-function(file) paste(readLines(file), collapse="\n")` could be useful.
Marek
A: 

Another way is to create a .R script with query definition

# content of biglongquery.R
query <- "
SELECT
    very_long_list_of_fields
FROM ...
"

and then use it in the main script using

source("biglongquery.R")
Marek