env参数在system2中不起作用?

时间:2016-10-07 02:25:55

标签: r r-faq

我正在尝试使用system2运行命令并使用env参数设置环境变量,但似乎没有设置。我在Linux上,所以这应该工作[在帮助文件中它提到env有时在Windows中不起作用。)

有谁知道如何在system32中设置环境变量?

E.g。

system2('echo', args='foobar')
# foobar # as expected
system2('echo', args='$X', env="X=foobar")
#   # <-- nothing is printed. as if I had just done `echo`
# I expect to see 'foobar' echoed.

# pretty sure the above environment specification is right, but just in case
system2('echo', args='$X', env=c(X='foobar'))
# sh: 1: foobar: not found

# just to show it can work
system('X=foobar; echo $X')
# foobar

我现在只使用system作为解决方法,但system帮助文件继续讨论我应该如何使用system2。 (如果这是一个错误,我在哪里提交?)

> sessionInfo()
R version 3.2.5 (2016-04-14)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu precise (12.04.5 LTS)

locale:
 [1] LC_CTYPE=en_AU.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_AU.UTF-8        LC_COLLATE=en_AU.UTF-8    
 [5] LC_MONETARY=en_AU.UTF-8    LC_MESSAGES=en_AU.UTF-8   
 [7] LC_PAPER=en_AU.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_AU.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base  

1 个答案:

答案 0 :(得分:5)

由于转到shell的命令只是paste(c(env, shQuote(command), args), collapse = " "),你可以这样做:

system2("echo", args = "$X", env = c("X=foobar;"))