20

Is there a way to provide the code to Rscript -e in multiple lines?

This is possible in vanilla R

R --vanilla <<code
a <- "hello\n"
cat(a)
code

But using Rscript I get two different things depending on the R version.

# R 3.0.2 gives two ignores
Rscript -e '
quote> a <- 3+3
quote> cat(a, "\n")
quote> '
# ARGUMENT 'cat(a,~+~"' __ignored__
# ARGUMENT '")' __ignored__

Rscript -e 'a <- 3+3;cat(a, "\n")'
# ARGUMENT '")' __ignored__

# R 2.15.3 gives an ignore for the multiline, but it works with semicolons
Rscript -e '
quote> a <- 3+3
quote> cat(a, "\n")
quote> '
# ARGUMENT 'cat(a,~+~"\n")' __ignored__

Rscript -e 'a <- 3+3;cat(a, "\n")'
6

I'm clearly using the wrong syntax. What is the proper way to do this?

nachocab
  • 13,328
  • 21
  • 91
  • 149

1 Answers1

13

Update: I think the problem was spacing and quotes. This worked (on windows):

Rscript -e "a <- 3+3; cat(a,'\n')"
6

On Mac, you have to escape the escape character:

Rscript -e 'a <- 3+3; cat(a,"\\n")'

You can also put each expression separately.

Rscript -e "a <- 3+3" -e "cat(a)"
Carlos Cinelli
  • 11,354
  • 9
  • 43
  • 66
  • 2
    `Rscript -e "a <- 3+3; cat(a,'\n')"` doesn't work for me on a mac with R 3.0.2, but using the `-e` could be a decent workaround – nachocab Feb 12 '14 at 18:34
  • I am using windows right now, because I am at work. But I have a Mac at home. I will check it there when I get home. – Carlos Cinelli Feb 12 '14 at 20:18
  • 1
    This works in MacOS: Rscript -e 'a <- 3+3; cat(a,"\\n")' – Hansi Feb 12 '14 at 20:44
  • 1
    @Hansi you're right. I didn't know that R 3 chokes with `"\n"` but R 2 doesn't. I wonder why – nachocab Feb 12 '14 at 21:57
  • to expand on @Hansi's comment: it's also worth noting that the outer quotes must be single and the inner quotes must be double or this method doesn't work. – Thomas Ingalls Dec 10 '15 at 18:43