Search code examples
rcmdimagemagickrstudiosystem

Change working directory to use ImageMagick command from a markdown doc in RStudio


I'd like to use the "montage" command in ImageMagick to combine two images in a folder into one image, within a R-markdown file in RStudio. I'd use the magick library's image_montage function, but I can't find out how to alter preferences (e.g., geometry, tile, etc - http://www.imagemagick.org/Usage/montage/).

I can do it outside RStudio using the terminal by navigating to the folder containing the images, clicking on the address bar, typing cmd - this shows that I am in the correct folder:

C:\Users\JaneDoe\Desktop\test>

then in the command window:

montage left.jpg logo.jpg new.jpg

This creates a new image called "new.jpg" in that folder.

I'm struggling to use the system command to do the same thing from inside a markdown chunk in RStudio, however.

I can't change the working directory apparently - let's say my project directory is "C:/Users/JaneDoe" - I can't change it to "C:\Users\JaneDoe\Desktop\test" in a markdown chunk.

I've tried many iterations of the following code to try and get it to work from within RStudio, with no luck. What am I doing wrong? Note: my "real" file path does have a space in it.

system("cd C:\\Users\\JaneDoe\\Desktop\\test && montage left.jpg logo.jpg new2.jpg")

Solution

  • Unfortunately, I do not know RStudio enough to add anything more. But knowing ImageMagick and things like PHP exec() and Python subprocess, the logical thing would be to provide the full path to your images and not try to change directories. So something like this should work, if your working directory is set in RStudio as "C:\Users\JaneDoe":


    system("montage Desktop\test\left.jpg Desktop\test\logo.jpg Desktop\test\new2.jpg")

    In some system-like calls in other software (such as AppleScript), you might have to add the full path to montage as these other tools may not use the same PATH environment variable as your system does, but RStudio supplies your workspace to the system call in this case.