13

I'm using bash to pipe data through an Rscript like so: cat random.csv | Rscript test.R arg >| delete.csv

My aim is to use the R package readr to both read stdin and write stdout. I found the answer to stdin here.

test.R

#!/usr/bin/Rscript
suppressMessages(library(readr))

args  <- commandArgs(trailingOnly = TRUE)

df.in <- read_csv(file("stdin"))

write_csv(df.in, path = stdout())

The above code produces the following error message at the command line:

Error Message

Error in path.expand(path) : invalid 'path' argument
Calls: write_csv -> write_delim -> normalizePath -> path.expand
Execution halted

I have also tried write_csv(df.in, file("stdout")) and write_csv(df.in, stdout()) producing the same error message.

For reproducibility, here's a link to a random.csv

Definition of variables, by WHO for the Global Tuberculosis Report [43kb]

Luke Singham
  • 1,536
  • 2
  • 20
  • 38

4 Answers4

26

There is a format_csv function for that in readr. Use this instead of write_csv:

cat(format_csv(df.in))
m0nhawk
  • 22,980
  • 9
  • 45
  • 73
  • 2
    Thanks @m0nhawk - this is very close. The error message no longer appears. However, the `delete.csv` has all data printed on a single row when there should be multiple rows. If you wrap your answer with `cat()` the result is right on the money. e.g. `cat(format_csv(df.in))`. Update and I'll accept your answer. – Luke Singham Mar 01 '16 at 22:19
2

for reading from stdin:

df.in <- read_csv(paste(collapse = "\n", readLines(file("stdin"))))

for writing to stdout:

writeLines(format_csv(tibble(a=c(1,2))), stdout())

#or
writeLines(format_csv(df.in), stdout())

Kudos to: jimhester

xhudik
  • 2,414
  • 1
  • 21
  • 39
0

With write.table and write.csv from base R, you can specify the filename as "" to print to STDOUT:

file: either a character string naming a file or a connection open
      for writing.  ‘""’ indicates output to the console.

Example:

$ Rscript -e 'write.csv(head(mtcars),"",quote=F)'
,mpg,cyl,disp,hp,drat,wt,qsec,vs,am,gear,carb
Mazda RX4,21,6,160,110,3.9,2.62,16.46,0,1,4,4
Mazda RX4 Wag,21,6,160,110,3.9,2.875,17.02,0,1,4,4
Datsun 710,22.8,4,108,93,3.85,2.32,18.61,1,1,4,1
Hornet 4 Drive,21.4,6,258,110,3.08,3.215,19.44,1,0,3,1
Hornet Sportabout,18.7,8,360,175,3.15,3.44,17.02,0,0,3,2
Valiant,18.1,6,225,105,2.76,3.46,20.22,1,0,3,1
nisetama
  • 7,764
  • 1
  • 34
  • 21
-2

You can use write.table:

write.table(x, file = "foo.csv", sep = ",", col.names = NA,
        qmethod = "double")

See the help page: https://stat.ethz.ch/R-manual/R-devel/library/utils/html/write.table.html

motobói
  • 1,687
  • 18
  • 24