将数据帧的每列乘以向量的对应值

时间:2017-04-03 15:53:07

标签: r vector dataframe

我有以下数据框和向量:

dframe <- as.data.frame(matrix(1:9,3))
vector <- c(2,3,4)

我想将dframe的每一列乘以相应的vector值。这不会做:

> vector * dframe
  V1 V2 V3
1  2  8 14
2  6 15 24
3 12 24 36 

dframe的每个乘以vector的相应值,而不是每个。有没有惯用的解决方案,还是我坚持for周期?

2 个答案:

答案 0 :(得分:4)

以下是使用sweep

的其他选项
sweep(dframe, 2, vector, "*")
#  V1 V2 V3
#1  2 12 28
#2  4 15 32
#3  6 18 36

或使用col

dframe*vector[col(dframe)]

答案 1 :(得分:1)

您可以使用Map

as.data.frame(Map(`*`, dframe, vector))

#  V1 V2 V3
#1  2 12 28
#2  4 15 32
#3  6 18 36
相关问题