2013-10-23 5 views
21

私はデータセットをプロットする前に構築しようとしています。私は、関数の工場gammaplot.ff()を使用することを決めたと私のコードの最初のバージョンは、次のようになります(数字から要素へのrbind()/ cbind()の変換を避ける

PowerUtility1d <- function(x, delta = 4) { 
    return(((x+1)^(1 - delta))/(1 - delta)) 
} 
PowerUtility1d <- Vectorize(PowerUtility1d, "x") 

# function factory allows multiparametrization of PowerUtility1d() 
gammaplot.ff <- function(type, gamma) { 
    ff <- switch(type, 
       original = function(x) PowerUtility1d(x/10, gamma), 
       pnorm_wrong = function(x) PowerUtility1d(2*pnorm(x)-1, gamma), 
       pnorm_right = function(x) PowerUtility1d(2*pnorm(x/3)-1, gamma) 
      ) 
    ff 
} 

gammaplot.df <- data.frame(type=numeric(), gamma=numeric(), 
          x=numeric(), y=numeric()) 
gammaplot.gamma <- c(1.1, 1.3, 1.5, 2:7) 
gammaplot.pts <- (-1e4:1e4)/1e3 

# building the data set 
for (gm in gammaplot.gamma) { 
    for (tp in c("original", "pnorm_wrong", "pnorm_right")) { 
    fpts <- gammaplot.ff(tp, gm)(gammaplot.pts)  
    dataChunk <- cbind(tp, gm, gammaplot.pts, fpts) 
    colnames(dataChunk) <- names(gammaplot.df) 
    gammaplot.df <- rbind(gammaplot.df, dataChunk) 
    } 
} 

# rbind()/cbind() cast all data to character, but x and y are numeric 
gammaplot.df$x <- as.numeric(as.character(gammaplot.df$x)) 
gammaplot.df$y <- as.numeric(as.character(gammaplot.df$y)) 

全体のデータフレームは、文字データが含まれている、判明したので、私は手動で戻ってそれを変換する必要があり、しばらくに連れて行ってくれました最初に見つけてください!)。 SO検索indicatesタイプ変数が文字なのでこれが起こる。 (!データセットを構築しながら、あなたが文字データのパフォーマンスの問題を想像することができます)これを避けるために、私は、コードを少し変更:

gammaplot.ff <- function(type, gamma) { 
    ff <- switch(type, 
       function(x) PowerUtility1d(x/10, gamma), 
       function(x) PowerUtility1d(2*pnorm(x)-1, gamma), 
       function(x) PowerUtility1d(2*pnorm(x/3)-1, gamma) 
      ) 
    ff 
} 

for (gm in gammaplot.gamma) { 
    for (tp in 1:3) { 
    fpts <- gammaplot.ff(tp, gm)(gammaplot.pts)  
    dataChunk <- cbind(tp, gm, gammaplot.pts, fpts) 
    colnames(dataChunk) <- names(gammaplot.df) 
    gammaplot.df <- rbind(gammaplot.df, dataChunk) 
    } 
} 

これは私のために正常に動作しますが、私は自明文字のパラメータを失い、その欠点です。すべてのデータを文字に暗黙的に変換せずにファンクションファクトリの最初のバージョンを保持する方法はありますか?

同じ結果を達成する別の方法がある場合は、私はそれを試してみてうれしいです。

+0

@トーマス、あなたの短い答えは明らかに間違っています。受け入れられた答えを見てください。また、代替手段なしで何かをしてはならないと述べることは建設的ではありません。 –

答えて

48

rbindcbindの代わりにrbind.data.framecbind.data.frameを使用できます。

+0

'rbind'が正しく動作するので(データフレームを引数の1つとして検出するため)、' cbind.data.frame'だけを使用するだけでも十分です。 それほどシンプルだとは思わなかった! – tonytonov

+2

注意: 'cbind.data.frame()'を名前リストと組み合わせて使うと、意図していなかったn x mの行列が作成されます。これは意図していない場合、 'cbind()'の代わりに 'cbind.data.frame()'を使う前に、名前付きリストを 'unlist()'するだけです。 – BurninLeo

+6

'cbind.data.frame(tp、gm、gammaplot.pts、fpts、stringsAsFactors = FALSE)' stringsAsFactors = Fを使用していない場合は、引き続き要素を持つことができます。 – mtelesha

関連する問題