简体   繁体   English

计算列表中列的平均值和标准差

[英]Calculate the mean and sd of a column within a list

If I have this list 如果我有这个清单

set.seed(123)
thelist <- list(a=data.frame(x1=rnorm(10), x2=rnorm(10)),
                b=data.frame(x1=rnorm(10), x2=rnorm(10)),
                c=data.frame(x1=rnorm(10), x2=rnorm(10)))

> thelist
$a
            x1         x2
1  -0.56047565  1.2240818
2  -0.23017749  0.3598138
3   1.55870831  0.4007715
4   0.07050839  0.1106827
5   0.12928774 -0.5558411
6   1.71506499  1.7869131
7   0.46091621  0.4978505
8  -1.26506123 -1.9666172
9  -0.68685285  0.7013559
10 -0.44566197 -0.4727914

$b
           x1          x2
1  -1.0678237  0.42646422
2  -0.2179749 -0.29507148
3  -1.0260044  0.89512566
4  -0.7288912  0.87813349
5  -0.6250393  0.82158108
6  -1.6866933  0.68864025
7   0.8377870  0.55391765
8   0.1533731 -0.06191171
9  -1.1381369 -0.30596266
10  1.2538149 -0.38047100

$c
            x1          x2
1  -0.69470698  0.25331851
2  -0.20791728 -0.02854676
3  -1.26539635 -0.04287046
4   2.16895597  1.36860228
5   1.20796200 -0.22577099
6  -1.12310858  1.51647060
7  -0.40288484 -1.54875280
8  -0.46665535  0.58461375
9   0.77996512  0.12385424
10 -0.08336907  0.21594157

How can I calculate the mean and sd of x1 and x2 for each list item (eg a:c? The output would be a data frame (or object or...) with column names mean_x1 and mean_x2 . Each row would correspond to a list name (eg a:c). I have seen a number of similar posts, but none that address the specific question. 如何为每个列表项(例如a:c)计算x1和x2的meansd ,输出将是一个数据列(或对象或...),其列名分别为mean_x1mean_x2 ,每行对应一个列表名称(例如a:c),我看到了许多类似的帖子,但是都没有解决特定的问题。

How about: 怎么样:

do.call(rbind,lapply(thelist, function(d) data.frame(sd=lapply(d,sd),mean=lapply(d,mean))))

Output: 输出:

      sd.x1     sd.x2      mean.x1   mean.x2
a 0.9537841 1.0380734  0.074625644 0.2086220
b 0.9308092 0.5273024 -0.424558873 0.3220446
c 1.0825182 0.8564451 -0.008715537 0.2216860

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM