Luke Singham
Luke Singham

Reputation: 1736

Is it possible to write stdout using write_csv() from 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]

Upvotes: 15

Views: 3558

Answers (4)

nisetama
nisetama

Reputation: 8923

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

Upvotes: 1

motob&#243;i
motob&#243;i

Reputation: 1815

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

Upvotes: -2

xhudik
xhudik

Reputation: 2444

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

Upvotes: 2

m0nhawk
m0nhawk

Reputation: 24218

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

cat(format_csv(df.in))

Upvotes: 27

Related Questions