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+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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.