rsystem

Call a variable in a system command


I'm calling image magick in an R script, which is working fine (see line 1). However, I'd like to get it call a variable from R and change the name of the output file depending on this variable. I've tried to paste it into the system command (see line 2), but it doesn't seem to work. Does anyone know how to do this?

line 1:

system("magick convert -delay 40 *.png K-10 trail_cost - 3 K.gif")  

line 2:

system(paste("magick convert -delay 40 *.png K - ", K, "trail_cost - ", trail_cost, ".gif"))

Solution

  • You have some extra spaces, I would use paste0 and check if identical before running:

    K = 10
    trail_cost = "3 K"
    
    # check if identical before running system
    identical("magick convert -delay 40 *.png K-10 trail_cost - 3 K.gif",
              paste0("magick convert -delay 40 *.png K-", K, " trail_cost - ", trail_cost, ".gif"))
    # [1] TRUE
    

    Note: Avoid using spaces in filenames.

    K = 10
    trail_cost = 3
    
    paste0("magick convert -delay 40 *.png K-", K, "trail_cost-", trail_cost, "K.gif")