给定数据帧(df)
Hup Hop testA testB
Y Hi 1 1
N Lo 2 2
Y Mi 3 3
N No 4 4
Y Hi 5 5
N Lo 6 6
Y Mi 7 7
N No 8 8
Y Hi 9 9
N Lo 10 10
Y Mi 11 11
N No 12 12我需要testA和testB的描述性统计数据(平均值和sd),用于分组变量Hup和Hop。我想要这样的东西。
hup testA.mean testA.sd testB.mean testB.sd
y 7 3.742 7 3.742
n 6 3.742 6 3.742
hop testA.mean testA.sd testB.mean testB.sd
hi etc Etc etc Etc
lo etc Etc etc Etc
mi etc Etc etc Etc例如,使用ddply(df,~hup,summarise,mean=round(mean(testA),3),sd=round(sd(testA),3))可以解决部分问题。但是我想加速这个过程:学习如何使用R。所以,我想:
lapply(df[ , c("testA", "testB")], function(x){ ddply(df, ~df[ , c("hup")], function(x) {mean(x)} )})
这是不工作的,它返回NA,错过SD,并报告只有结果为hup。
问:如何生成多变量组的描述性统计数据?
发布于 2014-02-27 11:26:35
对于显示,我认为来自tabular包的tables函数是最简单的:
library(tables)
tabular(Hup + Hop ~ (testA + testB)*((n = 1) + mean + sd), data = df)
## testA testB
## mean sd n mean sd n
##Hup N 7 3.742 6 7 3.742 6
## Y 6 3.742 6 6 3.742 6
##Hop Hi 5 4.000 3 5 4.000 3
## Lo 6 4.000 3 6 4.000 3
## Mi 7 4.000 3 7 4.000 3
## No 8 4.000 3 8 4.000 3U还可以将tabular()对象包装在latex()中,以LaTeX语法输出表。
发布于 2014-02-27 11:10:21
library(reshape2)
library(plyr)
dfm <- melt(df, id.vars = c("Hup", "Hop"))
splits <- list(.(Hup, variable), .(Hop, variable))
## or something like
## splits <- data.frame(rbind(head(names(dfm), -2), "variable"))
lapply(splits, ddply, .data = dfm, .fun = summarize, mean = mean(value), sd = sd(value))
## [[1]]
## Hup variable mean sd
## 1 N testA 7 3.741657
## 2 N testB 7 3.741657
## 3 Y testA 6 3.741657
## 4 Y testB 6 3.741657
## [[2]]
## Hop variable mean sd
## 1 Hi testA 5 4
## 2 Hi testB 5 4
## 3 Lo testA 6 4
## 4 Lo testB 6 4
## 5 Mi testA 7 4
## 6 Mi testB 7 4
## 7 No testA 8 4
## 8 No testB 8 4https://stackoverflow.com/questions/22066438
复制相似问题