Background
I have a dataframe of probability distributions that I would like to calculate statistical summaries for:
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")
Approach
Step 1: I wrote a function to calculate the summaries and returning 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 = ''))
}
Step 2: I would like to add a new column to my dataframe called stats
priors$stats <- ddply(priors,
.(name, distn, parama, paramb),
function(x) summary.stats(x$distn, x$parama, x$paramb))$V1
Question 1:
what is the proper way to do this? I get an error when I try
ddply(priors,
.(name, distn, parama, paramb),
transform,
stats = function(x) summary.stats(x$distn, x$parama, x$paramb))
Question 2: (extra credit)
Is there a more efficient way to code the summary.stats
function, i.e., with less 'if's'?
update
Thanks to Shane and Joshua for clearing this up for me.
I also found a question that should be helpful for others trying to do a plyr operation on every row of a dataframe