Multiply columns in a data frame by a vector

前端 未结 3 1998
死守一世寂寞
死守一世寂寞 2020-12-31 05:44

What I want to do is multiply all the values in column 1 of a data.frame by the first element in a vector, then multiply all the values in column 2 by the 2nd element in the

3条回答
  •  生来不讨喜
    2020-12-31 06:23

    Or simply diagonalize the vector, so that each row entry is multiplied by the corresponding element in v1:

    c1 <- c(1,2,3)
    c2 <- c(4,5,6)
    c3 <- c(7,8,9)
    d1 <- as.matrix(cbind(c1,c2,c3))
    v1 <- c(1,2,3)
    
    d1%*%diag(v1)
    
         [,1] [,2] [,3]
    [1,]    1    8   21
    [2,]    2   10   24
    [3,]    3   12   27
    

提交回复
热议问题