Split code over multiple lines in an R script

Viewed 321182

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.

8 Answers

The glue::glue function can help. You can write a string on multiple lines in a script but remove the line breaks from the string object by ending each line with \\:

glue("some\\
     thing")

something

I know this post is old, but I had a Situation like this and just want to share my solution. All the answers above work fine. But if you have a Code such as those in data.table chaining Syntax it becomes abit challenging. e.g. I had a Problem like this.

mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, Geom:=tstrsplit(files$file, "/")[1:4][[4]]][time_[s]<=12000]

I tried most of the suggestions above and they didn´t work. but I figured out that they can be split after the comma within []. Splitting at ][ doesn´t work.

mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, 
    Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, 
    Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, 
    Geom:=tstrsplit(files$file, "/")[1:4][[4]]][`time_[s]`<=12000]

This will keep the \n character, but you can also just wrap the quote in parentheses. Especially useful in RMarkdown.

t <- ("
this is a long
string
")

There is no coinvent way to do this because there is no operator in R to do string concatenation.

However, you can define a R Infix operator to do string concatenation:

`%+%` = function(x,y) return(paste0(x,y))

Then you can use it to concat strings, even break the code to multiple lines:

s = "a" %+%
    "b" %+%
    "c"

This will give you "abc".

Related