Sue
Sue

Reputation: 23

For loop to sum each column of a matrix in R

For the following matrix:

my_matrix<-matrix(seq(from=1,to=100,by=2))

If I wanted the sum of each column calculated I would just put the command as follows: colSums(my_matrix)

However, I need to create equivalence to colSums(my_matrix) without using the colSums function and instead use for loop.

Some please help!!!

Upvotes: 0

Views: 1337

Answers (2)

Kill3rbee Lee Mtoti
Kill3rbee Lee Mtoti

Reputation: 246

Sue, you can try this simple loop, hope it helps address your issue.

sum <- 0
for(i in 1:ncol(my_matrix)){
  sum[i] <- sum(my_matrix[,i])
}

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388807

If you explicitly want to use for loop here is one way :

mat <- matrix(1:50, byrow = TRUE, ncol = 10)
all_vals <- numeric(ncol(mat))
for (i in seq(ncol(mat))) {
   all_vals[i] <- sum(mat[, i])
}

all_vals
#[1] 105 110 115 120 125 130 135 140 145 150

which gives same value as

colSums(mat)
#[1] 105 110 115 120 125 130 135 140 145 150

Upvotes: 0

Related Questions