Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write stdout using write_csv() from readr?

Tags:

bash

r

readr

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]

like image 670
Luke Singham Avatar asked Mar 01 '16 12:03

Luke Singham


2 Answers

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

cat(format_csv(df.in))
like image 170
m0nhawk Avatar answered Oct 20 '22 21:10

m0nhawk


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

like image 2
xhudik Avatar answered Oct 20 '22 20:10

xhudik