LoginSignup
8
7

More than 5 years have passed since last update.

Rの中で環境を使い分ける

Last updated at Posted at 2014-05-01

 RStudioでガリガリプログラミングしてると自作の関数やオブジェクトが増えすぎて、せっかくEnvironmentウィンドウがあるのに見通しが非常に悪くなることが有ります。
 一時変数を環境に残したくない、といった場合は無名関数内で処理してみます。

sample1.R
(function(){
    a <- 1:3
    b <- 4:6
    ans <<- a*b
})()
cat(ans)
# 4 10 18
ls()
# "ans"

 オブジェクトは作成したいけど、.GlobalEnvに表示させたくない場合。

sample2.R
myEnv <- new.env()
assign("myFunc",
       function(x){
           x^2 + 2*x + 2
       },
       myEnv)
attach(myEnv)
rm(myEnv)
ls()
# character(0)
myFunc(1:5)
# [1]  5 10 17 26 37
find("myFunc")
# [1] "myEnv"

 オブジェクトの環境を独立させたいけど、パッケージ化するほどではないといった場合におすすめ。

8
7
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
8
7