Home > Blockchain >  How to sum vectors where each vector is x_i?
How to sum vectors where each vector is x_i?

Time:09-08

I've been working with vectors like

x_1 = runif(1000, min = 0, max = 1)
x_2 = runif(1000, min = 0, max = 1)
x_3 = runif(1000, min = 0, max = 1)
.
.
x_200 = runif(1000, min = 0, max = 1)

So I wanted to make a for loop to make the sum of each vector

for (i in 1:200){
   sumxi <- sum(paste("x_", i)
}

But it throws me the error "Error in sum(paste0("x_",i)) : invalid 'type' (character) of argument" So im asking for any help with a website or something like that to know how to work with vectors that have the same name that only change the index

CodePudding user response:

I would do this differently. I suggest storing your vectors in a list (not hanging out in the open) and then using the lapply function which applies a given function to all members of the list.

If your list is something called like list_x then:

list_x = list(x_1 = runif(1000, min = 0, max = 1), 
x_2 = runif(1000, min = 0, max = 1), 
x_3 = runif(1000, min = 0, max = 1))

Then to get the sum of each vector in your list it is real simple:

lapply(list_x, FUN = sum)

$x_1 [1] 497.7253

$x_2 [1] 505.065

$x_3 [1] 501.2293

Perhaps you don't like the format in which case you could just unlist it:

unlist(lapply(list_x, FUN = sum))
     x_1      x_2      x_3 
497.7253 505.0650 501.2293 

You won't get the same numbers because these vectors are randomly generated but the output looks similar.

To access each member of the list like the first one just index it:

print(list_x[1]) 

Output is a thousand observations. To get the sum of the first vector in your list:

sum(list_x[[1]])

The double brackets sort of remove the vector name so it is just numbers to sum.

CodePudding user response:

I would make a variable with all the data fields to be summed, and an empty data.frame to place the results. Then loop over the variables:

x_var<-paste("x", 1:3, sep="_")
x_data<-data.frame(x_names=x_var)
for (i in 1:length(x_var)) {
  x_data[i,"x_sum"]<-sum(get(x_var[i]))
}
  x_names    x_sum
1     x_1 507.4773
2     x_2 496.5080
3     x_3 508.9271

An sapply() method:

x_var<-paste("x", 1:3, sep="_")
x_data<-data.frame(x_names=x_var)
# x_data$x_sum<-sapply(x_var, FUN = function(x) {sum(get(x))})
x_data$x_sum<-sapply(mget(x_var), FUN = sum)
  x_names     xsum
1     x_1 507.4773
2     x_2 496.5080
3     x_3 508.9271

CodePudding user response:

You can generate all 200 tests in one line of code, then convert the vector to a matrix and sum the columns:

x <- runif(200 * 1000, min = 0, max = 1)
m <- matrix(x, ncol = 200)
sums <- colSums(m)

CodePudding user response:

  • We can use get to search for an object by name and initialize sumxi to zero before the loop
sumxi <- 0
for (i in 1:200){
    sumxi <- sumxi   sum(get(paste0("x_", i)))
}
  • Related