背景我該如何重寫這段代碼才能按照預期使用plyr/ddply?
我有概率分佈的數據幀,我想計算統計彙總爲:
priors <- structure(list(name = c("theta1", "theta2", "theta3", "theta4",
"theta5"), distn = c("gamma", "beta", "lnorm", "weibull", "gamma"),
parama = c(2.68, 4, 1.35, 1.7, 2.3), paramb = c(0.084, 7.2, 0.69, 0.66, 3.9),
another_col = structure(c(3L, 4L, 5L, 1L, 2L
), .Label = c("1", "2", "a", "b", "c"), class = "factor")),
.Names = c("name", "distn", "parama", "paramb", "another_col"), row.names = c("1",
"2", "3", "4", "5"), class = "data.frame")
方法
第1步:我寫了一個函數來計算摘要並返回mean(lcl, ucl)
summary.stats <- function(distn, A, B) {
if (distn == 'gamma' ) ans <- c(A*B, qgamma(c(0.05, 0.95), A[ ], B))
if (distn == 'lnorm' ) ans <- c(exp(A + 1/2 * B^2), qlnorm(c(0.05, 0.95), A, B))
if (distn == 'beta' ) ans <- c(A/(A+B), qbeta(c(0.05, 0.95), A, B))
if (distn == 'weibull') ans <- c(mean(rweibull(10000,A,B)), qweibull(c(0.05, 0.95), A, B))
if (distn == 'norm' ) ans <- c(A, qnorm(c(0.05, 0.95), A, B))
ans <- (signif(ans, 2))
return(paste(ans[1], ' (', ans[2], ', ', ans[3],')', sep = ''))
}
第2步:我想補充一個新的列到我的數據幀稱爲stats
priors$stats <- ddply(priors,
.(name, distn, parama, paramb),
function(x) summary.stats(x$distn, x$parama, x$paramb))$V1
問題1:
什麼是做到這一點的正確方法?我得到一個錯誤,當我嘗試
ddply(priors,
.(name, distn, parama, paramb),
transform,
stats = function(x) summary.stats(x$distn, x$parama, x$paramb))
問題2:(加分)
有沒有更有效的方式來編碼summary.stats
功能,即以較少的「如果的」?
更新
感謝巴蒂爾和約書亞清除這件事對我來說。
我還發現一個問題,應該對別人有幫助試圖do a plyr operation on every row of a dataframe
我認爲這是他希望新列名稱是「統計」。我已經將它添加到了他的函數版本中。 – 2010-12-09 22:34:25