[R] computing the average and standard deviation for many sets of triplicates, using "R-approach"

hadley wickham h.wickham at gmail.com
Wed Jun 18 18:05:57 CEST 2008


On Wed, Jun 18, 2008 at 9:17 AM, Daren Tan <daren76 at hotmail.com> wrote:
>
> Below example has 4 sets of triplicates, without using for loop and iteratively cbind the columns, what is the "R-approach" of generating a matrix of 8 columns that are the averages and standard deviations ? The average and standard deviation columns should be side by side i.e. A.mean A.sd B.mean B.sd C.mean C.sd D.mean D.sd
>

t <- matrix(rnorm(120), ncol=12)
colnames(t) <- paste(rep(LETTERS[1:4], each=3), 1:3, sep=".")

# First get your data into a more useful format,
# where explanatory variables are explicitly encoded by
# columns in a data frame.

library(reshape)
tm <- melt(t)
tm <- cbind(colsplit(tm$X2, "\\.", c("trt", "block")), tm)
tm$X2 <- NULL
tm <- rename(tm, c("X1" = "rep"))

head(tm)

# tm is now much easier to work with most R functions
# for your case, you can also use cast in the reshape package:

cast(tm, block ~ trt, c(mean, sd))
cast(tm, . ~ trt, c(mean, sd))

# for more info about the reshape package, see http://had.co.nz/reshape

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list