views:

422

answers:

4

In R, how can I import the contents of a multiline text file (containing SQL) to a single string?

The sql.txt file looks like this:

SELECT TOP 100 
 setpoint, 
 tph 
FROM rates

I need to import that text file into an R string such that it looks like this:

> sqlString
[1] "SELECT TOP 100 setpoint, tph FROM rates"

That's so that I can feed it to the RODBC like this

> library(RODBC)
> myconn<-odbcConnect("RPM")
> results<-sqlQuery(myconn,sqlString)

I've tried the readLines command as follows but it doesn't give the string format that RODBC needs.

> filecon<-file("sql.txt","r")
> sqlString<-readLines(filecon, warn=FALSE)
> sqlString
[1] "SELECT TOP 100 "                              "\t[Reclaim Setpoint Mean (tph)] as setpoint, "
[3] "\t[Reclaim Rate Mean (tph)] as tphmean "       "FROM [Dampier_RC1P].[dbo].[Rates]"           
> 
A: 

try paste(sqlString, collapse=" ")

Aidan Cully
+2  A: 

The versatile paste() command can do that with argument collapse="":

R> lines <- readLines("/tmp/sql.txt")
R> lines
[1] "SELECT TOP 100 " " setpoint, "     " tph "           "FROM rates"     
R> sqlcmd <- paste(lines, collapse="")
R> sqlcmd
[1] "SELECT TOP 100  setpoint,  tph FROM rates"
R> 
Dirk Eddelbuettel
Thanks Dirk - that works, except the string looks like this "SELECT TOP 100\t setpoint,\t tph\t FROM rates\t". Just needed to add gsub("\t","", sqlcmd)
Tommy O'Dell
Well what I copied had not tabs, in any event the SQL parser will probably ignore the tabs anyway and you found the `gsub()` -- all good.
Dirk Eddelbuettel
+1  A: 

Here's the final version of what I'm using. Thanks Dirk.

fileconn<-file("sql.txt","r")           
sqlString<-readLines(fileconn)          
sqlString<-paste(sqlString,collapse="")
gsub("\t","", sqlString)
library(RODBC)
sqlconn<-odbcConnect("RPM")
results<-sqlQuery(sqlconn,sqlString)
library(qcc)
tph <- qcc(results$tphmean[1:50], type="xbar.one", ylim=c(4000,12000), std.dev=600)
close(fileconn)
close(sqlconn)
Tommy O'Dell
A: 

I use sql <- gsub("\n","",sql) and sql <- gsub("\t","",sql) together.

MW Frost