Calling external program from R with multiple commands in system

爱⌒轻易说出口 提交于 2019-11-29 07:27:52

Construct the string you want to execute with paste and feed that to system:

for(i in 1:10){
cmd=paste("export FOO=",i," ; echo \"$FOO\" ",sep='')
system(cmd)
}

Note the use of sep='' to stop paste putting spaces in, and back-quoting quote marks in the string to preserve them.

Test before running by using print(cmd) instead of system(cmd) to make sure you are getting the right command built. Maybe do:

if(TESTING){print(cmd)}else{system(cmd)}

and set TESTING=TRUE or FALSE in R before running.

If you are going to be running more than one shell command per system call, it might be better to put them all in one shell script file and call that instead, passing parameters from R. Something like:

cmd = paste("/home/me/bin/dojob.sh ",i,i+1)
system(cmd)

and then dojob.sh is a shell script that parses the args. You'll need to learn a bit more shell scripting.

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