【问题标题】:Multiply each column of a data frame by the corresponding value of a vector [duplicate]将数据框的每一列乘以向量的相应值[重复]
【发布时间】:2017-04-03 15:53:06
【问题描述】:

我有以下数据框和向量:

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 循环?

【问题讨论】:

  • t(t(dframe) * vector) 呢?
  • 这是重复的。一种方法是df * rep(vec, each=nrow(df))

标签: r vector dataframe


【解决方案1】:

这是另一个使用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)]

【讨论】:

  • 我最喜欢第二个选项。我认为它会更快,如果你上瘾并想尝试一系列类似的操作:) 在我的例子中,在将 dframe 乘以 vector 之后,我还想添加 center 到它(另一个向量)。用这种方法我可以写vec2mat &lt;- col(dframe); dframe*vector[vec2mat] + center[vec2mat]
【解决方案2】:

你可以使用Map:

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

#  V1 V2 V3
#1  2 12 28
#2  4 15 32
#3  6 18 36

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多