如何对数字列表元素求和 [英] How to sum a numeric list elements

查看:62
本文介绍了如何对数字列表元素求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一种允许对列表的数值求和(或计算平均值)的优雅方法.例如

I'm wondering about an elegant way allowing to sum (or calculate a mean) a numeric values of a list. e.g.

x <- list( a = matrix(c(1,2,3,4), nc=2), b = matrix(1, nc=2, nr=2))

想要得到

x[[1]]+x[[2]] 

或平均值:

(x[[1]]+x[[2]])/2

推荐答案

您可以使用 Reduce 连续将二元函数应用于列表中的元素.

You can use Reduce to successively apply a binary function to elements in a list.

Reduce("+",x)
     [,1] [,2]
[1,]    2    4
[2,]    3    5

Reduce("+",x)/length(x)
     [,1] [,2]
[1,]  1.0  2.0
[2,]  1.5  2.5

这篇关于如何对数字列表元素求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆