简体   繁体   中英

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?

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.

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')"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM