2016-09-27 10 views
3

Box-Cox変換に最適な「ラムダ」パラメータを探しています。R関数内の別の関数に線形モデルを渡す

MASSパッケージの実装を使用しているため、モデルを作成してラムダを抽出するだけで済みます。

library(MASS) 

find_lambda <- function(x) { 
    # Function to find the best lambda for the Box-Cox transform 

    my_tmp <- data.frame(x = x) # Create a temporary data frame, to use it with the lm 
    str(my_tmp) # Gives the expected output 

    the_lm <- lm(x ~ 1, data = my_tmp) # Creates the linear model, no error here 
    print(summary(the_lm)) # Prints the summary, as expected 

    out <- boxcox(the_lm, plotit=FALSE) # Gives the error 

    best_lambda <- out$x[which.max(out$y)] # Extracting the best fitting lambda 
    return(best_lambda) 
} 

find_lambda(runif(100)) 

それは次のエラーを与える:

Error in is.data.frame(data) : object 'my_tmp' not found 

非常に同じコードは関数の外で働いていることは興味深いものがある。ここ

は、関数のコードです。言い換えれば、何らかの理由で、 boxcoxの機能が MASSパッケージからグローバル環境で変数を探しています。

私は本当に理解していない、正確に何が起こっている...任意のアイデアがありますか?

P.S.私はソフトウェア/ハードウェア仕様を提供していません。なぜなら、このエラーは私の友人のノートパソコンのいくつかに首尾よく複製されていたからです。

P.P.S.私は予報パッケージの初期の問題を解決する方法を見つけましたが、私はまだこのコードが動作していない理由を知りたいと思います。

答えて

0

boxcoxあなたのデータを見つけることができません。スコープの問題が原因である可能性があります。
boxcox機能にデータをフィードできます。

find_lambda <- function(x) { 
    # Function to find the best lambda for the Box-Cox transform 

    my_tmp <- data.frame(x = x) # Create a temporary data frame, to use it with the lm 
    str(my_tmp) # Gives the expected output 

    the_lm <- lm(x ~ 1, data = my_tmp) # Creates the linear model, no error here 
    print(summary(the_lm)) # Prints the summary, as expected 

    out <- boxcox(the_lm, plotit=FALSE, data = my_tmp) # feed data in here 

    best_lambda <- out$x[which.max(out$y)] # Extracting the best fitting lambda 
    return(best_lambda) 
} 

find_lambda(runif(100)) 
3

関数呼び出しを操作するときに呼び出しが実行された環境をユーザーが提供するパッケージが必ずしも素晴らしい仕事をするとは限りません。 yqrlm呼び出しから要求されていない場合は、boxcox機能を再実行するlmをしようとするので、あなたのための最速の修正は

the_lm <- lm(x ~ 1, data = my_tmp, y=True, qr=True) 

the_lm <- lm(x ~ 1, data = my_tmp) 

から行を変更することであろうこれらのパラメータをupdateコールで取得すると、機能スコープ内で問題が発生する可能性があります。

0

なぜボックスコックスがフィッティングをしないのですか?

find_lambda <- function(x) { 
    # Function to find the best lambda for the Box-Cox transform 

    my_tmp <- data.frame(x = x) # Create a temporary data frame, to use it with the lm 

    out <- boxcox(x ~ 1, data = my_tmp, plotit=FALSE) # Gives the error 

    best_lambda <- out$x[which.max(out$y)] # Extracting the best fitting lambda 
    return(best_lambda) 
} 

私はあなたのスコープの問題はeval(call, parent.frame())my_tmpboxcox環境には存在しません呼び出すupdate.defaultであると思います。私が間違っている場合は、私を修正してください。

関連する問題