Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

loading - How to load packages in R automatically?

Could you suggest me a way for loading packages in R automatically? I mean, I want to start a session in R without needing to use library('package name') several times. Suppose I downloaded all packages I'll want to use the next time I start R.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Put library(foo) in your .Rprofile file or set R_DEFAULT_PACKAGES: see ?Rprofile ...

In particular (because ?Rprofile is long and potentially intimidating):

If you want a different set of packages than the default ones when you start, insert a call to ‘options’ in the ‘.Rprofile’ or ‘Rprofile.site’ file. For example, ‘options(defaultPackages = character())’ will attach no extra packages on startup (only the ‘base’ package) (or set ‘R_DEFAULT_PACKAGES=NULL’ as an environment variable before running R). Using ‘options(defaultPackages = "")’ or ‘R_DEFAULT_PACKAGES=""’ enforces the R system default.

Since you probably do want all of the default packages loaded, and then extra ones in addition (rather than, say, not loading some of the default packages), you can either put

library("mypackage1")
library("mypackage2")
[etc.]

or using options(defaultPackages=...):

options(defaultPackages=c(getOption("defaultPackages"),
       "mypackage1","mypackage2", ... [etc.]))

in your .Rprofile to append your desired packages to the standard defaults.

edit (copied from comment) re getting this to work in Rstudio: http://rstudio.org/docs/using/workspaces suggests that Rstudio executes .Rprofile and then "Performs the other actions described in R Startup [ http://stat.ethz.ch/R-manual/R-patched/library/base/html/Startup.html ]" (which is the same as ?Rprofile). It is ambiguous whether it looks at Rprofile.site or not.

edit #2: according to comment below, it does work with a recent version of Rstudio.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...