1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RでEDAする際に、書き捨ての関数をGlobal環境ではなくPackage環境下にロードするようにする

Posted at

目的

RでEDAをしていく中で、書き捨ての関数を書いていくと毎回実行するのが面倒になってくる。
また、Global環境も汚れてしまい、変数の表示が見づらくなる。
これらの問題について、作成した関数をpackage環境下にロードできるようにして解決する。

流れ

パッケージ作成コマンド実行

devtools::create(".")

以下のように怒られるが、パッケージを作るわけではないのですべてyesで。

New project '現在のフォルダ名' is nested inside an existing project './', which is rarely a good idea.
If this is unexpected, the here package has a function, `here::dr_here()` that reveals why './' is regarded as a project.
Do you want to create anyway?

1: Not now
2: Nope
3: Yes

Selection: 3
√ Setting active project to 'C:/Users/kyusque/Desktop/amex'
√ Creating 'R/'
√ Writing 'DESCRIPTION'
Package: amex
Title: What the Package Does (One Line, Title Case)
Version: 0.0.0.9000
Authors@R (parsed):
    * First Last <first.last@example.com> [aut, cre] (YOUR-ORCID-ID)
Description: What the package does (one paragraph).
License: `use_mit_license()`, `use_gpl3_license()` or friends to
    pick a license
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.2
√ Writing 'NAMESPACE'
Overwrite pre-existing file 'amex.Rproj'?

1: No way
2: Not now
3: Yup

Selection: 3
√ Writing 'amex.Rproj'
√ Adding '^amex\\.Rproj$' to '.Rbuildignore'
√ Adding '^\\.Rproj\\.user$' to '.Rbuildignore'
√ Setting active project to '<no active project>'

Rフォルダにzzz.Rファイルを作成後、.onLoad(libname, pkgname)関数を追加

パッケージ作成の観点からはあまりよくないが、.onLoad(libname, pkgname)関数を作成して、よく使うパッケージをインポートしておくと、書き捨ての解析の際に便利。

R/zzz.R
.onLoad <- function(libname, pkgname){
  pacman::p_load(
    tidyverse
    , caret
    , summarytools
    , data.table
    , RSQLite
    , DBI
    , dbplyr
    , doParallel
    , tictoc
  )
}

my_function_1 <- function(...){
...
}

main.Rの先頭にdevtools::load_all(".")を追加

devtools::load_all(".")を実行すると、Rフォルダ内のファイルがすべて実行され、package環境内でロードされる。

main.R
devtools::load_all(".")

...解析

my_function_1(...)

以上で、Global環境を汚さずに書き捨ての関数をロードできるようになる。
この後は、利用目的に合わせて適宜Rフォルダ内にファイルを作って関数を追記していくことで、main.Rをよりシンプルな形で書けるようになる。

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?