2016-03-01 56 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

相關問題