是否可以使用readr中的write_csv()编写stdout?

时间:2016-03-01 12:20:18

标签: r bash readr

我正在使用bash通过Rscript来管道数据,如下所示: cat random.csv | Rscript test.R arg >| delete.csv

我的目标是使用Rreadr来读取stdin和写入stdout。我找到了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())

上面的代码在命令行中生成以下错误消息:

错误消息

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

我还尝试write_csv(df.in, file("stdout"))write_csv(df.in, stdout())生成相同的错误消息。

为了重现性,这里是random.csv

的链接

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

4 个答案:

答案 0 :(得分:9)

format_csv中有readr个功能。使用此代替write_csv

cat(format_csv(df.in))

答案 1 :(得分:1)

从stdin读取:

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

写给stdout:

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

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

感谢:jimhester

答案 2 :(得分:0)

您可以使用write.table

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

请参阅帮助页面:https://stat.ethz.ch/R-manual/R-devel/library/utils/html/write.table.html

答案 3 :(得分:0)

使用来自基础 R 的 write.tablewrite.csv,您可以将文件名指定为 "" 以打印到 STDOUT:

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

示例:

$ 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