Run .bat file using shell() in R

2020-06-23 08:43发布

问题:

I'm using the console of PDFSam to split and merge some PDF files. I can do this semi-automatically using .bat files, but I would like to do the whole thing in R.

This code in my .bat file works:

C:
cd "/Program Files/pdfsam/bin/"
run-console.bat -f "d:/delete/A_9.pdf" -o d:/delete -s BURST -overwrite split

But this "equivalent" code in my R shell command returns no errors, but doesn't seem to work.

shell('C: 
cd "/Program Files/pdfsam/bin/"
run-console.bat -f "d:/delete/A_9.pdf" -o d:/delete -s BURST -overwrite split')

Is there an option I'm missing in my shell command? I've tried a few of the options listed in ?shell to no avail.

I'm using windows XP and R version 2.13.1 (2011-07-08) Platform: i386-pc-mingw32/i386 (32-bit)

Thanks, Tom

回答1:

You could pass multiple commands to shell by concatenating them by &, so below should work:

shell('C: & cd C:/Program Files/pdfsam/bin & run-console.bat -f "d:/delete/A_9.pdf" -o d:/delete -s BURST -overwrite split')

But as a workaround you could temporary change R working directory:

current.wd <- getwd()
setwd("C:/Program Files/pdfsam/bin")
shell('run-console.bat -f "d:/delete/A_9.pdf" -o d:/delete -s BURST -overwrite split')
setwd(current.wd)

If you do it frequent write a function:

shell.in.dir <- function(dir, ...) {
    current.wd <- getwd()
    on.exit(setwd(current.wd))
    setwd(dir)
    shell(...)
}

shell.in.dir("C:/Program Files/pdfsam/bin",
    'run-console.bat -f "d:/delete/A_9.pdf" -o d:/delete -s BURST -overwrite split')


回答2:

This isn't exactly an answer to your question, but you might try system("youBatFile.bat") as an alternative.



标签: r pdf cmd