R, passing variables to a system command

风格不统一 提交于 2019-12-30 05:00:14

问题


Using R, I am looking to create a QR code and embed it into an Excel spreadsheet (hundreds of codes and spreadsheets). The obvious way seems to be to create a QR code using the command line, and use the "system" command in R. Does anyone know how to pass R variables through the "system" command? Google is not too helpful as "system" is a bit generic, ?system does not contain any examples of this.

Note - I am actually using data matrices rather than QR codes, but using the term "data matrix" in an R question will lead to havoc, so let's talk QR codes instead. :-)

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

fails, as do the variants I have tried with "paste". Any suggestions gratefully received.


回答1:


Let's say we have the variable x that we want to pass on to dmtxwrite, you can pass it on like:

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

or alternatively using paste:

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

but I prefer sprintf in this case.




回答2:


Also making use of base::system2 may be worth considering as system2 provides args argument that can be used for that purpose. In your example:

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

would return:

 a -o image.png

which is equivalent to running echo in the terminal. You may also want to redirect output to text files:

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


来源:https://stackoverflow.com/questions/10651640/r-passing-variables-to-a-system-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!