【问题标题】:How to pass several files to a command function and output them to different files?如何将多个文件传递给命令函数并将它们输出到不同的文件?
【发布时间】:2017-11-14 13:09:31
【问题描述】:

我有一个由 50 个文件组成的目录,这里是关于文件名称的摘录:

    input1.txt
    input2.txt    
    input3.txt
    input4.txt

我在 R 中编写脚本,但我在其中使用“系统”使用 bash 命令 我有一个系统命令 X,它获取一个文件并将其输出到一个文件 示例:

X input1.txt output1.txt

我希望 input1.txt 输出到 output1.txt,input2.txt 输出到 output2.txt 等等。

我一直在尝试这个:

    for(i in 1:50)
    {
     setwd("outputdir");
     create.file(paste("output",i,".txt",sep=""));
     setwd("homedir");
     system(paste("/usr/local/bin/command" , paste("input",i,".txt",sep=""),paste("/outputdir/output",i,".txt",sep="")));
    }

我做错了什么?我在 system 行收到错误,它说不正确的字符串常量,我不明白。我是否以错误的方式应用了系统命令?

有没有办法在不通过粘贴命令将它们放入系统的情况下获取所有输入文件和输出文件?

【问题讨论】:

  • 我认为您的意思是 file.create,而不是 create.file。此外,您的命令是否甚至要求在写入之前创建输出文件 - 通常情况并非如此。 i <- 1:4; cmds <- sprintf('"%s" "%s/input%d.txt" "%s/output%d.txt"', cmd, indir, i, outdir, i) 将一次性创建所有命令。
  • 这是在我的 R 脚本中吗?和 cmd ,是我要使用的命令吗?我不需要像使用系统时那样在它周围加上“”吗?

标签: r bash file


【解决方案1】:

在 R 中有一种非常简单的方法,可以在不使用系统命令的情况下将文件复制到新目录。这还具有在不同操作系统上具有交叉能力的好处(只需更改文件结构)。

修改代码来自:"Copying files with R" by Amy Whitehead

使用你的文件运行方法 1:50 我在这里有一些伪代码。您需要将 current.folder 和 new.folder 更改为

# identify the folders
current.folder <- "/usr/local/bin/command"
new.folder <- "/outputdir/output"

# find the files that you want
i <- 1:50
# Instead of looping we can use vector pasting to get multiple results at once!
inputfiles <- paste0(current.folder,"/input",i,".txt")
outputfiles <- paste0(new.folder,"/output",i,".txt")

# copy the files to the new folder
file.copy(inputfiles, outputfiles)

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2019-12-24
    • 2020-03-21
    • 2022-11-25
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多