[Solved] vector addition using R


You can use ls() to list all variables in the global environment and restrict the output of it by pattern argument. 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.

# 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 

1

solved vector addition using R