Home > OS >  Run cmd command from within R
Run cmd command from within R

Time:05-17

I want to trigger/run a certain cmd command from within R. I found the functions system, system2 and shell, but am a bit lost on how to exactly use them.

So if I would do it directly in Windows, I'd open the cmd and then run the following command:

"C:\Program Files\LatentGOLD6.0\lg60" "C:\Users\USER\myfile.lgs" /b /o "C:\Users\USER\myfile.html" /h

However, I struggle with how and where I'd specify such a command in R so that it runs the thing. All of the mentioend functions above require a character string, but since I need to pass the paths with quotes, I'm actually not sure how I can glue all of this together.

Any ideas?

So here's my current code:

program_path <- "C:\Program Files\LatentGOLD6.0\lg60"
lgs_path     <- "C:\Users\USER\myfile.lgs"
out_path     <- "C:\Users\USER\myfile.html"

batchline <- paste0(program_path, " ", lgs_path, " /b /o ", out_path, " /h")

system(batchline)
system2(batchline)

Alternative also doesn't work: batchline <- paste0("'", program_path, "'", " ", "'", lgs_path, "'", " /b /o ", "'", out_path, "'", " /h")

CodePudding user response:

Use r"{...}" if there are backslashes within the literal string as we do here or else double each backslash (see ?Quotes) or in some cases using forward slash in place of backslash will work. Then use sprintf to generate batchline.

program_path <- r"{C:\Program Files\LatentGOLD6.0\lg60}"
lgs_path     <- r"{C:\Users\USER\myfile.lgs}"
out_path     <- r"{C:\Users\USER\myfile.html}"

batchline <- sprintf("%s %s /b /o %s /h", program_path, lgs_path, out_path)

or if you want to surround each path with quotes then replace last line with:

batchline <- sprintf('"%s" "%s" /b /o "%s" /h', program_path, lgs_path, out_path)

CodePudding user response:

EDIT: updated bug where I initially used forward slashes.

ok, found a solution with the help of this here: Adding double quotes to string in R, i.e. wrapping the file paths into shQuote works.

program_path <- normalizePath("C:/Program Files/LatentGOLD6.0/lg60")
lgs_path     <- normalizePath("C:/Users/USER/myfile.lgs")
out_path     <- normalizePath("C:/Users/USER/myfile.html")

batchline <- paste0(shQuote(program_path),
                    " ",
                    shQuote(lgs_path),
                    " /b /o ",
                    shQuote(out_path),
                    " /h")

system(batchline)
  • Related