簡體   English   中英

使用 R 的向量加法

[英]vector addition using R

我有多個相同長度的向量命名為:

c1
c2
c3
.
.
cn

有什么方法可以使單個向量“c”對 c1 到 cn 的所有元素求和,即

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

您可以使用ls()列出全局環境中的所有變量,並通過pattern參數限制其輸出。 然后使用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"

獲取每個選定向量之和的兩種方法。

# 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