r - Easy way to combine mean and sd in one table using tapply? -


in r's tapply function, there easy way output multiple functions combined (e.g. mean , sd) in list form?

that is, output of:

tapply(x, factor, mean) tapply(x, factor, sd) 

to appear combined in 1 data frame.

here 2 approaches , few variations of each:

  1. in first approach use function returns both mean , sd.

  2. in second approach repeatedly call tapply, once mean , once sd.

we have used iris data set comes r code runs:

1) first solution

# input data x <- iris$sepal.length factor <- iris$species  ### solution 1 mean.sd <- function(x) c(mean = mean(x), sd = sd(x)) simplify2array(tapply(x, factor, mean.sd)) 

here 2 variations of above solution. use same tapply construct simplify using do.call. first gives similar result solution above , second transpose:

# solution 1a - use same mean.sd do.call("rbind", tapply(x, factor, mean.sd))  # solution 1b - use same mean.sd - result transposed relative last 2 do.call("cbind", tapply(x, factor, mean.sd)) 

2) second solution. second solution gives similar result 1 , 1a above:

### solution 2 - orientation same 1 , 1a mapply(tapply, c(mean = mean, sd = sd), moreargs = list(x = x, index = factor)) 

this same 2 except transpose @ end correspond 1b:

# solution 2a - same 2 except orientation transposed corresponds 1b t(mapply(tapply, c(mean = mean, sd = sd), moreargs = list(x = x, index = factor))) 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -