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!
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