ariggs154
ariggs154

Reputation: 29

Manipulate of an array in RStudio, specific column and rowSums

In RStudio, I have marray_1. I want to manipulate the array to calculate the sum of column j divided by the sum of specific rows, i and starting at the selected column, j.

For example, for the follow array I would want:

    marray_1 <- matrix(c(17, 8, 1, 27, 0, 16, 11, 32, 0, 0, 13, 66), nrow = 3, ncol = 4)
    
    (17)/(17+8+1+27)
    (8+16)/((16+11+32)+(8+1+27))
    (1+11+13)/((1+27)+(11+32)+(13+66)

I will be adding additional rows and columns to the array so I'm hoping to write the code to be able to incorporate additional rows and columns.

I currently have the following code:

    
      rows <- dim(marray_1)[1]
      columns <- dim(marray_1)[2]
      # Loops to calculate 
      for (j in 1:n.occasions){
         for(i in 1:nrow(marray_1)){
        array[i, j] <- colSums(marray_1)[j]/(sum(marray_1[i,j:n.occasions]))
      }
    }
    
    # Print the resulting array
    print(array)

I know the numerator is right but I'm struggling on how to calculate the denominator. Any help would be greatly appreciated!

Upvotes: 1

Views: 46

Answers (2)

jay.sf
jay.sf

Reputation: 72828

We want to divide the cumSums of the first nrow columns by the rowSums of sub-matrices defined by rows= from1st row to current j row, and columns= from j until ncol. Thus, we can simply say:

> rsq <- seq_len(nrow(M))
> colSums(M[, rsq])/sapply(rsq, \(j) sum(M[1:j, j:ncol(M)]))
[1] 0.3207547 0.2526316 0.1666667

Data:

> dput(M)
structure(c(17, 0, 0, 8, 16, 0, 1, 11, 13, 27, 32, 66), dim = 3:4)

Upvotes: 0

r2evans
r2evans

Reputation: 160447

Assuming you really meant to use byrow=TRUE in your call to matrix,

marray_1 <- matrix(c(17, 8, 1, 27, 0, 16, 11, 32, 0, 0, 13, 66), nrow = 3, ncol = 4, byrow = TRUE)
marray_1
#      [,1] [,2] [,3] [,4]
# [1,]   17    8    1   27
# [2,]    0   16   11   32
# [3,]    0    0   13   66

I think what you're looking for is

sapply(1:(ncol(marray_1)-1),
       function(cn) sum(marray_1[1:cn,cn]) / sum(marray_1[1:cn,cn:ncol(marray_1)]))
# [1] 0.3207547 0.2526316 0.1666667

Compared with your values:

c(
    (17)/(17+8+1+27),
    (8+16)/((16+11+32)+(8+1+27)),
    (1+11+13)/((1+27)+(11+32)+(13+66))
)
# [1] 0.3207547 0.2526316 0.1666667

Upvotes: 0

Related Questions