This week whilst doing some Alteryx work I needed to write an R script into the workflow that relied on a specific packaged to be installed upon my machine.
I navigated to the appropriate website for the library and downloaded it to my local machine; but then I had a thought. What happens when I distribute this workflow to my peers to run on their local machines?
So through some googling I began to form a script that would install the library, run the appropriate command lines, and then uninstall the library (we don’t want our end user to randomly have an R package installed on their machine unbeknown to them).
So here is the script…
## use the system info commands to gain the location of the users desktop
## Install the appropriate package (in this case “jpeg”) from the cloud CRAN mirror to the location given as the users desktop
install.packages(“jpeg”, repos = “https://cloud.r-project.org “, lib = UserName)
## Open the library
Library(jpeg, lib.loc = UserName)
## Run your R-script
image = readJPEG(“C:\\Users\\Ben Moss\\Pictures\\Stranger_to_Stranger_cover.jpg”)
df = data.frame(
red = matrix(image[,,1], ncol=1),
green = matrix(image[,,2], ncol=1),
blue = matrix(image[,,3], ncol=1)
## Uninstall any packages that you installed
remove.packages(“jpeg”, lib = UserName)
You may notice that if you were to run the script without the closing remove.packages() function that the library will appear on your desktop.
It is worth noting that you may receive an install error if you were to simply copy and paste this script, this is likely to be related to the CRAN mirror not being suitable, in which case you should select an appropriate CRAN mirror from this site, given your location.