2016-03-01 61 views
5

我使用bash管道数据通过Rscript像这样: cat random.csv | Rscript test.R arg >| delete.csv 是否可以使用readr中的write_csv()编写stdout?

我的目标是使用Rreadr这两个标准输入读取和写入标准输出。我找到了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]

回答

5

一个环节有一个format_csv功能,在readr。使用此而不是write_csv

cat(format_csv(df.in)) 
+2

感谢@ m0nhawk - 这是很接近。错误消息不再出现。但是,当应该有多行时,'delete.csv'将所有数据打印在一行上。如果你用'cat()'包装你的答案,那么结果是正确的。例如'猫(format_csv(df.in))'。更新,我会接受你的答案。 –

1

从标准输入读取:

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

相关问题