R - 在终端中使用用户输入文件

R - use user input file in terminal

我写了一个简单的脚本,它将一个 csv 文件作为输入,进行一些操作,然后 returns 一个 txt 文件。

1 bpseq <- read.csv(file = "/home/Desktop/bpseq.csv", header = FALSE)
2 names(bpseq) <- c("posi", "res", "posj") #bpseq has 3 columns
3 df <- data.frame(posi=integer(nrow(bpseq)),
4                 ...
5                 posj=character(nrow(bpseq)))
6 df$posi <- bpseq$posi
7 df$posj <- bpseq$posj
7 write.table(df, file = "/home/Desktop/bpseq_CLnotation.txt", col.names = F, row.names = F, sep = "\t")

这很好用,我可以 运行 它在 "Rscript mybeautifulscript.R" 的命令中成功。

但我希望用户能够选择输入文件! 我当然试过了

bpseq <- read.csv(file.choose())

当我在 RStudio 中 运行 它工作得很好,但我希望我的同事,对 R 不友好,能够在终端中 运行 它。

从这个错误 returns 我了解到 file.choose() 不是执行此操作的方法!该函数正在读取我的下一行代码,假设它是文件,当它是名称(bpseq)时,添加代码中的第 2 行。

Nathalie 写了一个很好的相关答案,在某些方面对我有帮助,但我仍然不知道在命令行中获取用户输入文件的正确方法。有人知道怎么做吗?

找到了! 添加到我的代码行 -1 和 0 并更改前一段代码中的第 1 行:

-1 args <- commandArgs(trailingOnly = TRUE)
 0 fn <- args[1]
 1 bpseq <- read.csv(fn, header = FALSE) 

运行 在终端中这样:

Rscript mybeautifulscript.R inputfile.csv