Fastest way to multiply matrix columns with vector elements in R

前端 未结 6 1766
失恋的感觉
失恋的感觉 2020-12-13 06:10

I have a matrix m and a vector v. I would like to multiply first column of matrix m by the first element of vector v, and

6条回答
  •  我在风中等你
    2020-12-13 06:39

    As @Arun points out, I don't know that you'll beat your solution in terms of time efficiency. In terms of code understandability, there are other options though:

    One option:

    > mapply("*",as.data.frame(m),v)
          V1  V2  V3
    [1,] 0.0 0.0 0.0
    [2,] 1.5 0.0 0.0
    [3,] 1.5 3.5 0.0
    [4,] 1.5 3.5 4.5
    

    And another:

    sapply(1:ncol(m),function(x) m[,x] * v[x] )
    

提交回复
热议问题