Search code examples
rmatrixarithmetic-expressions

Arithmetic operation (Difference) between a vector and a Matrix in R


I am facing this issue when I am trying to calculate the difference between list and matrix in R, it is giving me weird results.

matrix <- matrix(1:10,1:10,nrow = 10,ncol=10)

list1 <- seq(1:10)

diff <- list1-matrix

Below is the output that I am trying to achieve but it does not work. Please let me know what I am doing wrong.

Screenshot


Solution

  • We can do this with multiple ways

    1) Transpose the matrix, subtract from the vector and then do the transpose

    t(t(matrix)- list1)
    

    2) replicate the vector to make the lengths same and then do the difference

    matrix - list1[col(matrix)]
    

    3) Using sweep

    sweep(matrix, 2, list1, `-`)