计算单个列表总计并输出为向量

时间:2017-03-12 18:25:37

标签: r list vector lapply

我有一个包含1000个元素的列表,其元素是100个值的向量。我想对这些元素求和,但每次列表都有与输出相同的值。怎么办呢?

 [[1]]
  [1] ....

...

[[1000]]
 [1] 41.796588400  1.822177817  0.516105021 16.554318711 22.441116192 11.557223237
 [7] 11.610201393 14.126722844 11.165417165 17.024791387 97.744736046  1.053429931
 [13]  5.409970556 10.534262466  2.402112926 61.989253054 89.141315737  7.831002594
 [19]  0.229311742  1.167366732 74.131595409 26.837412033  0.315262754  3.662595556
 [25]  7.621307733  6.599907692  2.436551709 50.371429645  0.046652228 84.050028030
 [31]  2.547629448  8.308966616  9.566100355  1.324906725 35.296845475 80.754003596
 [37] 53.073032197  0.506524295  0.478822391 14.147898302  0.292336489 45.329947475
 [43] 25.455486564 20.790057839 12.622231025 38.933121408 41.196719977  3.762513880
 [49] 88.326438565  0.006009079 18.974940292 18.964924610  4.299943187  0.266114761
 [55] 16.597228049  1.030058767 15.304970202 12.220887655  2.229263654 18.506392124
 [61]  8.455070746  0.000839928  0.621677398 16.936509072 10.599982129  5.542332913
 [67]  0.773795046 20.199178278 33.488631341  4.624800890  0.069347211 11.352912859
 [73] 20.614961806  2.986133970  1.185518764 33.563723467 15.468933119  2.360548396
 [79]  8.237662458 50.279689216  1.307944799 17.654806254 42.129699374  2.352254185
 [85]  1.069597812 12.714936626  4.677094902  0.085737588 11.653287453 15.610804195
 [91]  5.489030702  0.202041121  2.849800157  5.284956342  0.128010723  5.731836865
 [97]  3.635845442 11.560654785  0.800697847  0.719558593

1 个答案:

答案 0 :(得分:0)

不是那么简单:

lapply(x, sum)

?这是我得到的:

> x <- list(rep(1,100), rep(2,100), rep(3,100))
> lapply(x,length)
[[1]]
[1] 100

[[2]]
[1] 100

[[3]]
[1] 100

> lapply(x,head)
[[1]]
[1] 1 1 1 1 1 1

[[2]]
[1] 2 2 2 2 2 2

[[3]]
[1] 3 3 3 3 3 3

> lapply(x,sum)
[[1]]
[1] 100

[[2]]
[1] 200

[[3]]
[1] 300