Multiply columns in a data frame by a vector

前端 未结 3 1992
死守一世寂寞
死守一世寂寞 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:17

    We can also replicate the vector to make the lengths equal and then multiply

    d1*v1[col(d1)]
    #  c1 c2 c3
    #1  1  8 21
    #2  2 10 24
    #3  3 12 27
    

    Or use sweep

    sweep(d1, 2, v1, FUN="*")
    

    Or with mapply to multiply the corresponding columns of 'data.frame' and elements of 'vector'

    mapply(`*`, d1, v1)
    

提交回复
热议问题