Weighted rowSums of a matrix

前端 未结 1 517
难免孤独
难免孤独 2021-01-21 17:04

I have a matrix like this:

I would like to sum every value of a single row but weighted.

Example: Given a specific row, the sum would be:



        
相关标签:
1条回答
  • 2021-01-21 17:32

    You are looking for a matrix-vector multiplication. For example, if you have a matrix:

    set.seed(0)
    A <- matrix(round(rnorm(9), 1), 3)
    #     [,1] [,2] [,3]
    #[1,]  1.3  1.3 -0.9
    #[2,] -0.3  0.4 -0.3
    #[3,]  1.3 -1.5  0.0
    

    And you have another vector x, which is what you called "ponderation":

    x <- round(rnorm(3), 1)
    #[1]  2.4  0.8 -0.8
    

    You can do

    drop(A %*% x)
    #[1]  4.88 -0.16  1.92
    

    The drop just convert the result single column matrix into a 1D vector.

    You can have a quick check to see this is what you want:

    sum(A[1, ] * x)
    #[1] 4.88
    
    sum(A[2, ] * x)
    #[1] -0.16
    
    sum(A[3, ] * x)
    #[1] 1.92
    

    Compared with rowSums(), you can also think such computation as a "weighted rowSums".


    At the moment, it seems more likely that you have a data frame rather than a matrix. You can convert this data frame to matrix by as.matrix().

    0 讨论(0)
提交回复
热议问题