将数据帧的每一列乘以向量的相应值 [英] Multiply each column of a data frame by the corresponding value of a vector

查看:46
本文介绍了将数据帧的每一列乘以向量的相应值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据帧和向量:

I have the following data frame and vector:

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

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

I would like to multiply each column of dframe by the corresponding value of vector. This won't do:

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

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

each row of dframe is multiplied by the corresponding value of vector, not each column. Is there any idiomatic solution, or am I stuck with a for cycle?

推荐答案

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

这篇关于将数据帧的每一列乘以向量的相应值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆