简体   繁体   English

使用 R 的向量加法

[英]vector addition using R

I have multiple vectors of same length named as:我有多个相同长度的向量命名为:

c1
c2
c3
.
.
cn

is there any way to make a single vector "c" have summation of all elements of c1 to cn ie有什么方法可以使单个向量“c”对 c1 到 cn 的所有元素求和,即

c = c1+c2+c3+c4..........cn

You can use ls() to list all variables in the global environment and restrict the output of it by pattern argument.您可以使用ls()列出全局环境中的所有变量,并通过pattern参数限制其输出。 Then get values of those variables using mget and row bind the values of the list using rbind and get row sum using rowSums function.然后使用mget获取这些变量的值,使用rbind行绑定列表的值,并使用rowSums函数获取行总和。

# create sample vectors
c1 <- c(1, 2)
c2 <- c(2, 4) 
c3 <- c(3, 2)
c30 <- c(1, 30)

c_vars <- ls(pattern = "c[0-9]", name = .GlobalEnv )  # to get values for name argument, try search()
c_vars
# [1] "c1"  "c2"  "c3"  "c30"

n <- 2   # specify the value of n
c_vars <- c_vars[c_vars %in% paste("c", 1:n, sep = '')]   # subset only the variables matching from 1:n

c_vars
# [1] "c1" "c2"

Two ways to get the sum of each selected vector.获取每个选定向量之和的两种方法。

# 1. It will work only when all vectors are of same length
rowSums(do.call("rbind", mget( c_vars ) ))
# c1 c2 
#  3  6 

# 2. It will work regardless of length of vectors.   
unlist(lapply(mget(c_vars), sum))
# c1 c2 
#  3  6 

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

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