'Install R packages from the command line
I need to build a reproducible R installation from the command line. Seems easy enough, so I created a file with my package names of interest, for example
packages.txt:
ggvis
glmnet
caret
The an R script called installPkgs.R:
f = read.csv('packages.txt', header=FALSE)
z = install.packages(f[,1], repos='https://cran.rstudio.com')
And then I should be able to run this from the command line:
Rscript installPkgs.R
When I do, the packages are downloaded but not installed. What am I missing?
Solution 1:[1]
Answering my own question so that the answer is obvious and not buried into the coimments.
In my code, the list of packages is being interpreted as a factor rather than character strings. So, I need to set the parameter in read.csv() or the global parameter stringsAsFactors = FALSE.
Urgh.
Solution 2:[2]
With a small change the above code can accept package names from the command line:
install.packages(commandArgs(trailingOnly = TRUE), repos='https://cran.rstudio.com')
So running:
Rscript installPkgs.R "ggvis" "glmnet" "caret"
should achieve the same result as the above without needing the text file.
Solution 3:[3]
Another solution that not even requires a script file - good choice for Dockerfile etc.:
Rscript -e "install.packages(c('ggvis', 'glmnet', 'caret'), repos='https://cran.rstudio.com')"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | KirkD-CO |
Solution 2 | Aidan Wood |
Solution 3 | vboerchers |