This problem is best addressed through example:
The setup
x1 <- c(1,4,5,6,7,1)
x2 <- c(1,1,2,3,4,1)
x3 <- c(3,4,5,6,7,1)
x4 <- c(1,2,3,5,7,2)
x5 <- c(6,2,3,9,7,2)
x6 <- c(5,2,4,3,2,3)
x7 <- c(6,4,3,1,8,3)
matrix <- t(data.frame(x1,x2,x3,x4,x5,x6,x7))
colnames(matrix)[6] <- "factor"```
my goal is to create a matrix, where matrix elements are calculated based on the column sum of elements in the group, excluding row (i). I then divide this by the number of elements in the group less 1. So 3 objects in group 1 implies a division by (3-1) =2.
for each group, as described by column 6 or "factor", I would like to calculate a corresponding matrix, and then bind these matrices together.
for group 1 the desired matrix is
output1 <- c(1+3/2, 1+4/2, 2+5/2 ...)
output2 <- c(1+3/2, 4+4/2, 5+5/2...)
output3 <- c(1+1/2, 4+1/2, 5+2/2, 6+3/2 ...)
mat_output1 <- rbind(output1, output2, output3)
for group 2 the desired matrix is
output4 <- c(6/1 , 2/1, 3/1, 9/1, 7/1 ...)
output5 <- c(1/1,2/1,3/1,5/1,7/1,2/1)
mat_output2 <- rbind(output4, output5)
and for group 3
output6 <- c(6/1,4/1,3/1,1/1,8/1,3/1)
output7 <- c(5/1,2/1,4/1,3/1,2/1,3/1)
mat_output3 <- rbind(output6, output7)
with desired output of the form:
mat_output <- rbind(mat_output1, mat_output2, mat_output3)
This approach instead adds up the each column at once and then subtracts each
ifrom the column sum.Some performance. Note, @Ronak provides a warning so I changed to the
dplyrsuggested code ofmutate_at(vars(-group_cols), ...)instead ofmutate_all(...). Also, while thedata.tableis in @akrun, I was about to edit it in before @akrun posted and it's basically @Ronak'sdplyrway that's been translated.@G. Fernando's solution takes about 20 seconds so I excluded it from the profile. @akrun's base solution is the fastest. I personally kind of like @Ronak's base the best as it reads well.