Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Rscript -e a multiline string?

Tags:

r

stdin

rscript

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?

like image 712
nachocab Avatar asked Feb 12 '14 16:02

nachocab


People also ask

How do you write a multiline string in a shell script?

For example, if we have a multiline string in a script, we can use the \n character to create a new line where necessary. Executing the above script prints the strings in a new line where the \n character exists.

How do you continue R code on new line?

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 "".

How do you type multiple lines in R?

The easiest way to create a multi-line comment in RStudio is to highlight the text and press Ctrl + Shift + C. You can just as easily remove the comment by highlighting the text again and pressing Ctrl + Shift + C.

How do you echo multiple lines?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.


1 Answers

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)"
like image 67
Carlos Cinelli Avatar answered Sep 19 '22 19:09

Carlos Cinelli