Split code over multiple lines in an R script

Curious2learn picture Curious2learn · Jun 13, 2011 · Viewed 260.3k times · Source

I want to split a line in an R script over multiple lines (because it is too long). How do I do that?

Specifically, I have a line such as

setwd('~/a/very/long/path/here/that/goes/beyond/80/characters/and/then/some/more')

Is it possible to split the long path over multiple lines? I tried

setwd('~/a/very/long/path/here/that/goes/beyond/80/characters/and/
then/some/more')

with return key at the end of the first line; but that does not work.

Thanks.

Answer

Joris Meys picture Joris Meys · Jun 13, 2011

Bah, comments are too small. Anyway, @Dirk is very right.

R doesn't need to be told the code starts at the next line. It is smarter than Python ;-) and will just continue to read the next line whenever it considers the statement as "not finished". Actually, in your case it also went to the next line, but R takes the return as a character when it is placed between "".

Mind you, you'll have to make sure your code isn't finished. Compare

a <- 1 + 2
+ 3

with

a <- 1 + 2 +
3

So, when spreading code over multiple lines, you have to make sure that R knows something is coming, either by :

  • leaving a bracket open, or
  • ending the line with an operator

When we're talking strings, this still works but you need to be a bit careful. You can open the quotation marks and R will read on until you close it. But every character, including the newline, will be seen as part of the string :

x <- "This is a very
long string over two lines."
x
## [1] "This is a very\nlong string over two lines."
cat(x)
## This is a very
## long string over two lines.

That's the reason why in this case, your code didn't work: a path can't contain a newline character (\n). So that's also why you better use the solution with paste() or paste0() Dirk proposed.