Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiline R expression from shell (with indentation)

I'm trying to achieve what you might naively write as:

R -e "
rmarkdown::render(
  'MyDocument.Rmd', 
  params = list(
    year = 2017
  ),
  output_file = 'ExampleRnotebook.html'
)
"

So that I can make nicely formatted submission scripts to run on a cluster.

I've tried some variants on the below, I'm wondering if there might be an alternative approach to do this with the R -f flag?

read -r -d '' EXP << EOF
rmarkdown::render(
  'MyDocument.Rmd',
  params = list(
    year = 2017
  ),
  output_file = 'ExampleRnotebook.html'
)
EOF
R -e "$EXP"

but I get a series of errors that look like this:

ARGUMENT 'params~+~=~+~list(' __ignored__

for the different lines of the expression, followed by:

> rmarkdown::render(
+ 
+ Error: unexpected end of input

To reproduce:

MyDocument.Rmd =

---
title: "R Notebook"
output: html_notebook
params: 
  year: 0000
---

```{r}
params$year

```

This works fine:

read -r -d '' EXP <<- EOF 
rmarkdown::render('MyDocument.Rmd', params = list(year = 2017 ), output_file = 'ExampleRnotebook.html')
EOF
R -e "$EXP"

but gets hard to read with longer param lists

like image 472
Richard J. Acton Avatar asked Jan 29 '26 23:01

Richard J. Acton


1 Answers

This works for me (R version 3.5.0):

R --no-save <<code
for(i in 1:3) {
  i + 
    2
}
print(i)

runif(5,
      1,10)
code

Note: line-breaks and paddings are intentional.

like image 189
zx8754 Avatar answered Feb 01 '26 12:02

zx8754



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!