R对向量列表中的元素X求和 [英] R sum element X in list of vector

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

问题描述

我刚开始做一些 R 脚本,但我无法解决这个问题.

I just started doing some R script and I can't figure out this problem.

我得到了一个向量列表

myListOfVector <- list(
     c(1,2), 
     c(1,2), 
     c(1,2), 
     c(1,2)
)

我想要的是基于元素位置的列表中每个向量的每个 X 元素的总和这样如果我有 3 个包含 (a, b, c) 的向量,我将得到列表或向量中每个 a、每个 b 和每个 c 的总和

what I want is the sum of each X element of each vector that are in my list base on the position of the element so that if I have 3 vector that contains (a, b, c), I will get the sum of each a, each b and each c in a list or vector

我知道每个向量的长度都是一样的

I know that each vector are the same length

我所追求的就是这样的

result <- sum(myListOfVector)
# result must be c(4, 8)

有人有想法吗?

我能够做到这一点的唯一方法是使用循环,但这需要很长时间,以至于我无法辞职.

The only way I've been able to do it is by using a loop but it take so much time that I can't resign to do it.

我尝试了一些 apply 和 lapply,但它们似乎不像我想要的那样工作,因为我一次只有一个向量.

I tried some apply and lapply but they don't seem to work like I want it to because all I have is one vector at a time.

精度:向量列表由我无法修改的函数返回如果可能的话,我需要一个有效的解决方案

Precision : The list of vector is returned by a function that I can't modify I need an efficient solution if possible

推荐答案

相同长度的向量列表可以用Reduce求和:

A list of vectors of the same length can be summed with Reduce:

Reduce(`+`, myListOfVector)

如@AnandaMahto 和@JanLuba 所述,将其放入matrix 并使用colSumsrowSums,在某些情况下可能更快;我不确定.

Putting it in a matrix and using colSums or rowSums, as mentioned by @AnandaMahto and @JanLuba, might be faster in some cases; I'm not sure.

旁注.OP 中的示例不是 list;相反,它应该像

Side note. The example in the OP is not a list; instead, it should be constructed like

myListOfVector <- list( # ... changing c to list on this line
     c(1,2), 
     c(1,2), 
     c(1,2), 
     c(1,2)
)

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

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