Calling external program from R with multiple commands in system

前端 未结 1 627
野的像风
野的像风 2020-12-18 04:46

I am new to programming and mainly I am able to do some scripts within R, but for my work I need to call an external program. For this program to work on the ubuntu\'s termi

相关标签:
1条回答
  • 2020-12-18 05:28

    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.

    0 讨论(0)
提交回复
热议问题