Split code over multiple lines in an R script

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


a <- 1 + 2 +

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."
## [1] "This is a very\nlong string over two lines."
## 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.

Leave a Comment