我知道如何让一个R脚本在给定文件名作为参数时执行我想要的操作,例如,如果我的R脚本叫做script
并包含:
#!/usr/bin/Rscript
path <- commandArgs()[1]
writeLines(readLines(path))
然后我可以从bash命令行运行:
Rscript script filename.Rmd --args dev='svg'
我成功地获取了filename.Rmd
的内容并将其回显给了我。如果我不是传递像filename.Rmd
这样的文件名作为上述参数,而是想从stdin
中传递文本,我尝试修改我的脚本以从stdin读取:
#!/usr/bin/Rscript
writeLines(file("stdin"))
但是我不知道如何构建这种情况下的命令行调用。我尝试将内容传送到管道中:
cat filename.Rmd | Rscript script --args dev='svg'
并且尝试重定向:
Rscript script --args dev='svg' < filename.Rmd
and either way I get the error:
Error in writeLines(file("stdin")) : invalid 'text' argument
我也尝试过open(file("stdin"))
。我不确定是我构造R脚本有误还是命令行参数有误,或者两者都有误。
writeLines
来读取而不是readLines
。 - hrbrmstrreadLines(file("stdin"))
代替open(file("stdin"))
解决了我的问题。 - cboettig