【问题标题】:R, passing variables to a system commandR,将变量传递给系统命令
【发布时间】:2012-05-25 23:16:12
【问题描述】:

我希望使用 R 创建一个二维码并将其嵌入 Excel 电子表格(数百个代码和电子表格)。显而易见的方法似乎是使用命令行创建二维码,并在 R 中使用“system”命令。有谁知道如何通过“system”命令传递 R 变量?谷歌不太有用,因为“系统”有点笼统,?system 不包含任何示例。

注意 - 我实际上使用的是数据矩阵而不是 QR 码,但是在 R 问题中使用术语“数据矩阵”会导致严重破坏,所以让我们来谈谈 QR 码。 :-)

system("dmtxwrite my_r_variable -o image.png")

失败了,就像我用“粘贴”尝试过的变体一样。任何建议都非常感谢。

【问题讨论】:

    标签: r shell variables cran


    【解决方案1】:

    假设我们有变量x 想要传递给dmtxwrite,你可以像这样传递它:

    x = 10
    system(sprintf("dmtxwrite %s -o image.png", x))
    

    或者使用paste:

    system(paste("dmtxwrite", x, "-o image.png"))
    

    但在这种情况下我更喜欢sprintf

    【讨论】:

    • 对此并不满意,但是:system(paste("echo", x, "| dmtxwrite -o image.png")) 完成了这项工作。感谢您让我按照正确的思路思考。
    【解决方案2】:

    还可以考虑使用base::system2,因为system2 提供了可用于该目的的args 参数。在您的示例中:

    my_r_variable <- "a"
    system2(
        'echo',
        args = c(my_r_variable, '-o image.png')
    )
    

    会返回:

     a -o image.png
    

    相当于在终端运行echo。您可能还想将输出重定向到文本文件:

    system2(
        'echo',
        args = c(my_r_variable, '-o image.png'),
        stdout = 'stdout.txt',
        stderr = 'stderr.txt'
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 2017-12-15
      • 2012-06-24
      • 1970-01-01
      • 2019-06-24
      • 2017-06-15
      • 1970-01-01
      相关资源
      最近更新 更多