1

I use Notepad++ for my R coding. However, when I write SQL queries for R:

tt <- "SELECT 
         *
       FROM
         myTable"

Notepadd++ reads the tab indentations and line returns into R. So I get something like this:

tt> "SELECT \n\t\t* \n\t\tFROM \n\t\tmyTable"

I see similar stuff when I put line breaks in my longer functions, etc.

This runs fine, of course, but it's really difficult to read in the console and other people want to look at it. Is there any way to format something so that it's readable in Notepad++ and then somehow remove the returns and tabs when I input it into the R console?

Jeffrey Kramer
  • 1,345
  • 6
  • 25
  • 43
  • [This question](http://stackoverflow.com/questions/455037/notepad-tabs-to-spaces) might help. But I would encourage you to use a more full featured IDE like RStudio or a full featured text editor. – Justin Oct 24 '13 at 18:10
  • That totally helped, thank you! I use R Studio for some things, I should probably use it for more. – Jeffrey Kramer Oct 24 '13 at 18:15
  • Rstudio has the same syntactical issues, it can't tell that a string is a bit of SQL code or just a strangely worded sentence. The confusing autoindentation is allayed, but syntax highlighting etc. is not available. – AdamO Oct 24 '13 at 18:42

1 Answers1

0

When I am writing SQL code to be called from R such as in the RODBC package, I often edit that code in another tab of my text editor and save it to a file with extension .sql. That way, I can take full advantage of the syntax highlighting and correct autoindentation if there is any. You can read that file into R using the readLines command.

However, if there's an error and the code is returned to you, this code does not print to the console in a readable format. You should print the error using the cat command.

For instance,

> con <- odbcConnect(someSqlServer, myUserId, myPassword)
> qry <- sqlQuery(con, '
select 
  nonExistentVars 

from 
  nonExistentTable as A 

inner join 
  otherNonExistentTable as B 

on A.fakeId = B.fakeId
')

> qry ## hard to read
"ERROR blah blah \nselect \n  nonExistentVars \n\nfrom \n  nonExistentTable as A \n\ninner join \n  otherNonExistentTable as B \n\non A.fakeId = B.fakeId\n"

> cat(qry) ## easy to read
ERROR blah blah
select 
  nonExistentVars 

from 
  nonExistentTable as A 

inner join 
  otherNonExistentTable as B 

on A.fakeId = B.fakeId
AdamO
  • 4,283
  • 1
  • 27
  • 39