VanessaOak
VanessaOak

Reputation: 3

Calculations within a matrix with internal, references that are anchored to columns within the matrix in R

I have a matrix and I would like to perform a calculation on each number in the matrix so that I get another matrix with the same dimensions only with the results of the calculation. This should be easy except that part of the equation is dependent on which column I am accessing because I will need to have an internal reference to the number at row [3,] within that column.

The equation I would like to apply is: output matrix value = input_matrix value at a given position + (1- (matrix value at [3,] and in the same column as the input matrix value))

For example, For (1,1) in the matrix the calculation would be 1+(1-3)

For position (1,2) in the matrix, the calculation would be 5+(1-7)

input_matrix<- matrix(1:12, nrow = 4, ncol = 3)

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

The output matrix should end up looking like this:

     [,1] [,2] [,3]
[1,]    -1   -1  -1
[2,]    0    0   0
[3,]    1    1   1
[4,]    2    2   2

I have tried doing something like this:

output_matrix<-apply(input_matrix,c(1,2), function(x) x+(1-(input_matrix[3,])))

but that gives me three matrices with the wrong dimensions as the output.

I am thinking that perhaps I can perhaps just modify the function in the above calculation to get this to work, or alternatively write something that iterates over each column of the matrix but I am not sure exactly how to do this in a way that gives me the output matrix that I want.

Any help would be greatly appreciated.

Upvotes: 0

Views: 41

Answers (2)

akrun
akrun

Reputation: 887501

We could also do this in a vectorized way

input_matrix + (1 - input_matrix[3,][col(input_matrix)])
#     [,1] [,2] [,3]
#[1,]   -1   -1   -1
#[2,]    0    0    0
#[3,]    1    1    1
#[4,]    2    2    2

Upvotes: 1

Ian Campbell
Ian Campbell

Reputation: 24838

I think this should work for you:

apply(input_matrix, margin = 2, function(x) x + (1 - x[3]))
     [,1] [,2] [,3]
[1,]   -1   -1   -1
[2,]    0    0    0
[3,]    1    1    1
[4,]    2    2    2

Upvotes: 1

Related Questions