具有公共前缀的所有变量向量的总和

时间:2017-12-14 15:09:38

标签: r

是否可以将所有矢量变量与一个公共前缀相加?

例如:

x1 <- c(1,2,3)
x2 <- c(4,5,6)
  .
  .
  .
xn <- c(n,n,n)

y = x1 + x2 + ... xn

变量xn(即前缀为x)的数量仅在运行时已知。

3 个答案:

答案 0 :(得分:3)

假设您的yx具有相同的维度,您可以尝试将所有变量捕获到列表中并应用求和操作。

> x2 <- c(4,5,6)
> x1 <- c(1,2,3)
> ls(pattern = "^x\\d+$") # this is regex for finding "x" and "digits", 
                          # ^ is start of string, $ is end of string
[1] "x1" "x2"
> sapply(ls(pattern = "^x\\d+$"), get, simplify = FALSE)
$x1
[1] 1 2 3

$x2
[1] 4 5 6

> out <- sapply(ls(pattern = "^x\\d+$"), get, simplify = FALSE)
> Reduce("+", out)
[1] 5 7 9

你也可以按照@ LyzandeR的建议使用mget,特别是如果是花哨的单行。

Reduce("+", mget(ls(pattern = "^x\\d+$")))

答案 1 :(得分:2)

您可以查看示例:

xx <- 1
xx2 <- 2
xx3 <- 3

#get the names of the variables containing xx
vars <- ls(pattern = 'xx')
#mget will get the variables from the names, unlist will add them in an atomic vector
sum(unlist(mget(vars)))
#[1] 6

答案 2 :(得分:0)

一个非常天真的解决方案可能是:

# first 2 vectors are of interest
x1 <- c(1,2,3)
x2 <- c(4,5,6)

# answer doesn't need to have z sum in it
z <- c(7,8,9)

# create a dummy answer vector, initialize it will all 0; length will be the length of single vector that we are adding
answer<-rep(0,length(x1))

# loop through each variable in current environment
for (var in ls()){
    # see if variable name begins with x
    if (startsWith(var,'x')){
        # add it to our answer
        answer = answer + get(var)
    }
}
# print the answer
print(answer)