LoginSignup
0
1

More than 5 years have passed since last update.

R:欲しいパッケージのうち未インストールのパッケージのみインストールする

Last updated at Posted at 2018-07-27

欲しいパッケージのうち、未インストールのパッケージのみインストールした時の備忘録_φ(・_・

環境

  • Mac OS X 12.6
  • RStudio 1.0.136

未インストールのパッケージのみインストールする

パッケージが既にインストール済みか判定し、未インストールの場合実際にインストールするに掲載の関数をベースにさせていただきました。

参考ページに掲載の関数
install.package.ifnot.exist <- function(name)
{
  is.exist <- name %in% rownames(installed.packages())
  if(!is.exist){install.packages(name)}
}

関数名考えるのが苦手なので、teramonagiさんの関数名を真似させてもらいつつ、
複数パッケージを処理できるように、以下のように手を加えました。

未インストールのパッケージのみインストールする
install.packages.ifnot.exist <- function()
{
  p <- readline("type packages you want :")
  p <- gsub(" ","",unlist(strsplit(p, ",")),fixed=T)
  is.exist <- p %in% rownames(installed.packages())
  if(length(p[!(is.exist)])>0){
    install.packages(p[!(is.exist)])}
}

# 出力結果
# > install.packages.ifnot.exist()
# type packages you want :ggplot2,reshape2

#  There is a binary version available but the source version is later:
#        binary source needs_compilation
# ggplot2  2.2.1  3.0.0             FALSE

# installing the source package ‘ggplot2’

#  URL 'https://cran.rstudio.com/src/contrib/ggplot2_3.0.0.tar.gz' を試しています 
# Content type 'application/x-gzip' length 2847050 bytes (2.7 MB)
# ==================================================
# downloaded 2.7 MB

#  strptime(xx, f <- "%Y-%m-%d %H:%M:%OS", tz = tz) で警告がありました: 
#   unknown timezone 'default/Asia/Tokyo'
# * installing *source* package ‘ggplot2’ ...
# **  パッケージ ‘ggplot2’ の解凍および MD5 サムの検証に成功しました 
# ** R
# ** data
# *** moving datasets to lazyload DB
# ** inst
# ** preparing package for lazy loading
# ** help
# *** installing help indices
# *** copying figures
# ** building package indices
# ** installing vignettes
# ** testing if installed package can be loaded
# * DONE (ggplot2)

# The downloaded source packages are in

# ‘/private/var/folders/t9/xk2j5yln4_dfmh518_4xvyw80000gn/T/RtmpzpaHdt/downloaded_packages’

ひとまずこれで完成です。
今回、関数内で入力ラインを呼び出したかったので、ごちゃごちゃ書きましたが、もし引数としてパッケージ名を入力する場合は下記をご参考までに。(冒頭の関数とほぼ同内容です)

未インストールのパッケージのみインストールする
install.packages.ifnot.exist <- function(name)
{
  is.exist <- name %in% rownames(installed.packages())
  if(length(name[!(is.exist)])>0){
    install.packages(name[!(is.exist)])}
}

# 使用例
# > install.packages.ifnot.exist( c("ggplot2","dplyr") )

たまにある、devtools使わないと落とせないパッケージには未対応です。
分岐文で書いていけば、できないことはなさそうですが・・今回はここまでです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1