a = matrix(1:25,5,5)
B = capture.output(for (X in 1:5){
A = c(min(a[,X]),quantile(a[,X],0.25),median(a[,X]),quantile(a[,X],0.75),max(a[,X]),mean(a[,X]),sd(a[,X])/m^(1/2),var(a[,X]))
cat(A,"\n")
})
matrix(B,8,5)
我想要做的是生成一个表,每个列在A中按顺序包含这些元素。我尝试使用矩阵,但似乎它在这里不起作用。有人可以帮忙吗?
| 1 | 2 | 3 | 4 | 5 |
|---------------------------------------------
| min | | | | | |
|---------------------------------------------
| 1st quartile | | | | | |
|---------------------------------------------
| median | | | | | |
|---------------------------------------------
| SEM | | | | | |
|---------------------------------------------
| VAR | | | | | |
以上是我希望表格的样子。
答案 0 :(得分:2)
您真的不想使用capture.output
来捕获数字输出。您可以创建用于存储输出的矩阵,或使用apply
,如下所示:
apply(a, 2, function(x)c(min(x), quantile(x, 0.25), mean(x), sd(x)/sqrt(length(x))))
(我没有添加你想要的所有统计数据。)这更符合R编程方式。
答案 1 :(得分:0)
或者
a <- data.frame(matrix(1:25,5,5))
fn <- function (x)
c(summary(x), Sd = sd(x), Var = var(x))
library(plyr)
colwise (fn) (a)
返回:
X1 X2 X3 X4 X5
Min. 1.000000 6.000000 11.000000 16.000000 21.000000
1st Qu. 2.000000 7.000000 12.000000 17.000000 22.000000
Median 3.000000 8.000000 13.000000 18.000000 23.000000
Mean 3.000000 8.000000 13.000000 18.000000 23.000000
3rd Qu. 4.000000 9.000000 14.000000 19.000000 24.000000
Max. 5.000000 10.000000 15.000000 20.000000 25.000000
Sd 1.581139 1.581139 1.581139 1.581139 1.581139
Var 2.500000 2.500000 2.500000 2.500000 2.500000
答案 2 :(得分:0)
或使用plyr:
> a<=data.frame(value=1:25,set=factor(rep(1:5,each=5)))
> summaryfn<=function(v)data.frame(
+ q0=min(v),q25=quantile(v,0.25),q50=median(v),
+ q75=quantile(v,0.75),q100=max(v),mean=mean(v),
+ sd=sd(v)^(1/2),var=var(v))
> g<-ddply(a,.(set),function(x)summaryfn(x$value))
> g
set q0 q25 q50 q75 q100 mean sd var
1 1 1 2 3 4 5 3 1.257433 2.5
2 2 6 7 8 9 10 8 1.257433 2.5
3 3 11 12 13 14 15 13 1.257433 2.5
4 4 16 17 18 19 20 18 1.257433 2.5
5 5 21 22 23 24 25 23 1.257433 2.5
> t(g[-1])
[,1] [,2] [,3] [,4] [,5]
q0 1.000000 6.000000 11.000000 16.000000 21.000000
q25 2.000000 7.000000 12.000000 17.000000 22.000000
q50 3.000000 8.000000 13.000000 18.000000 23.000000
q75 4.000000 9.000000 14.000000 19.000000 24.000000
q100 5.000000 10.000000 15.000000 20.000000 25.000000
mean 3.000000 8.000000 13.000000 18.000000 23.000000
sd 1.257433 1.257433 1.257433 1.257433 1.257433
var 2.500000 2.500000 2.500000 2.500000 2.500000
-Alex