Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to source an R script that read stdin

Tags:

r

stdin

I have the following two ways of reading from stdin. But the method using source() does not work. Does anybody know how to make the source() method work? Thanks.

~$ cat main.sh 
#!/usr/bin/env bash

set -v
cat main.csv | Rscript main.R
cat main.csv | R -q --vanilla <<EOF
source('main.R')
EOF
~$ cat main.R
f=read.csv(file('stdin'))
f
~$ ./main.sh
cat main.csv | Rscript main.R
> f=read.csv(file('stdin'))
> f
    X V1 V2
1   1  1 11
2   2  2 12
3   3  3 13
4   4  4 14
5   5  5 15
6   6  6 16
7   7  7 17
8   8  8 18
9   9  9 19
10 10 10 20
> 
cat main.csv | R -q --vanilla <<EOF
source('main.R')
EOF
Error in read.table(file = file, header = header, sep = sep, quote = quote,  : 
  no lines available in input
Calls: source ... withVisible -> eval -> eval -> read.csv -> read.table
Execution halted
like image 665
user1424739 Avatar asked Dec 07 '25 01:12

user1424739


1 Answers

This works:

cat main.csv | R -q --vanilla -e 'source("main.R")'

where the last line of main.R has been replaced with

print(f)
like image 162
flodel Avatar answered Dec 08 '25 15:12

flodel