Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

r

rodbc

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 editors and applications. I'd also like the ability to split the query across lines for better readability.

In the RODBC documentation, the paste function is used to build the query out of separate chunks, but I'd prefer something less kludgy and with fewer quotes and commas. Thanks for your help.

like image 960
MW Frost Avatar asked Oct 27 '09 13:10

MW Frost


People also ask

Can you write SQL in R?

Did you know that you can run SQL code in an R Notebook code chunk? To use SQL, open an R Notebook in the RStudio IDE under the File > New File menu. Start a new code chunk with {sql} , and specify your connection with the connection=con code chunk option.

How do SQL and R work together?

Not only can you easily retrieve data from SQL Sources for analysis and visualisation in R, but you can also use SQL to create, clean, filter, query and otherwise manipulate datasets within R, using a wide choice of relational databases. There is no reason to abandon your hard-earned SQL skills!

How do I get the last 3 characters of a string in SQL?

It could be this using the SUBSTR function in MySQL: SELECT `name` FROM `students` WHERE `marks` > 75 ORDER BY SUBSTR(`name`, -3), ID ASC; SUBSTR(name, -3) will select the last three characters in the name column of the student table.


1 Answers

If you're an old C programmer from way back, as I am, you might enjoy just using sprintf().

Borrowing Ian's example:

y<-"y1"
x<-"somethingorother"
query <- sprintf(
'SELECT DISTINCT x AS %s,
                 y AS %s,
 FROM tbl
 WHERE id=%%s
 AND num=%%d', x, y)

yields:

> cat(query,"\n")
SELECT DISTINCT x AS somethingorother,
                 y AS y1,
 FROM tbl
 WHERE id=%s
 AND num=%d 
like image 200
Harlan Avatar answered Oct 07 '22 18:10

Harlan