问题描述
我正在尝试将一个数据框 df
乘以一个向量 v
,以便产品是数据框,其中 i
行由 df [i,] * v
给出。我可以这样做,例如,通过
I'm trying to multiply a data frame df
by a vector v
, so that the product is a data frame, where the i
-th row is given by df[i,]*v
. I can do this, for example, by
df <- data.frame(A=1:5, B=2:6); v <- c(0,2)
as.data.frame(t(t(df) * v))
A B
1 0 4
2 0 6
3 0 8
4 0 10
5 0 12
I我确定必须有更多的R风格的方法(和一个非常简单的一个!),但没有任何事情在我的脑海里。我甚至尝试像
I am sure there has to be a more R-style approach (and a very simple one!), but nothing comes on my mind. I even tried something like
apply(df, MARGIN=1, function(x) x*v)
但仍然是不可读的结构,如 as.data.frame(t(。))
是必需的。
如何在这里找到一个高效优雅的解决方法?
but still, non-readable constructions like as.data.frame(t(.))
are required.
How can I find an efficient and elegant workaround here?
推荐答案
p>这也可以:
data.frame(mapply(`*`,df,v))
在该解决方案中,您正在利用 data.frame
是一种列表
,所以您可以迭代 df
和 v
同时使用 mapply
。
In that solution, you are taking advantage of the fact that data.frame
is a type of list
, so you can iterate over both the elements of df
and v
at the same time with mapply
.
不幸的是,您可以从 mapply
中输出的内容:简单列表
或矩阵
。如果你的数据很大,这可能会更有效:
Unfortunately, you are limited in what you can output from mapply
: as simple list
, or a matrix
. If your data are huge, this would likely be more efficient:
data.frame(mapply(`*`,df,v,SIMPLIFY=FALSE))
因为它会将其转换为列表
,它更有效地转换为 data.frame
。
Because it would convert it to a list
, which is more efficient to convert to a data.frame
.
这篇关于什么是正确的方式乘以数据框架的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!