简体   繁体   English

将一个数据帧乘以另一个数据帧中的每一行并聚合结果

[英]Multiply one dataframe by each row in another dataframe and aggregate result

I have one dataframe where each row contain weights.我有一个数据框,其中每一行都包含权重。 I want to multiply a second dataframe by each row of the first one and aggregate the results with rowsumS then cumprod.我想将第二个数据帧乘以第一个数据帧的每一行,然后用 rowsumS 然后 cumprod 聚合结果。 For each line in the first dataframe, I want to save one element as a result.对于第一个数据框中的每一行,我想保存一个元素作为结果。

I have achieved this using a for loop, however this is fairly inefficient, particularly for a dataframe with many rows.我已经使用 for 循环实现了这一点,但是这是相当低效的,特别是对于具有许多行的数据帧。

Is there a way to to this without a for loop?没有for循环有没有办法做到这一点? maybe using tidyverse.也许使用 tidyverse。

x=runif(4*6)
x=matrix(x,nrow=4,ncol=6)
x_df=as.data.frame(x)

y=rnorm(3*6)
y=matrix(y,nrow=3,ncol=6)
y_df=as.data.frame(y)

ret=rep(NA, nrow(x_df))

for (i in 1:nrow(x_df)){
  rets=as.data.frame(mapply('*',y_df,x_df[i,]))
  rets=tail(cumprod(1+rowSums(rets,na.rm = TRUE)),1)
  ret[i]=rets
}

the vector rets contain the desired result.向量rets包含所需的结果。

Any of the following would work:以下任何一项都可以:

Base R:基数 R:

apply(tcrossprod(y, x) + 1, 2, prod)
[1]  0.3222529  0.1435537 -0.3998603 -2.1293011

Using matrixStats :使用matrixStats

matrixStats::rowProds(tcrossprod(x, y) + 1)
[1]  0.3222529  0.1435537 -0.3998603 -2.1293011

matrixStats::colProds(tcrossprod(y, x) + 1)
[1]  0.3222529  0.1435537 -0.3998603 -2.1293011

your code:你的代码:

set.seed(1)
x=runif(4*6)

x=matrix(x,nrow=4,ncol=6)
x_df=as.data.frame(x)

y=rnorm(3*6)
y=matrix(y,nrow=3,ncol=6)
y_df=as.data.frame(y)

ret=rep(NA, nrow(x_df))

for (i in 1:nrow(x_df)){
  rets=as.data.frame(mapply('*',y_df,x_df[i,]))
  rets=tail(cumprod(1+rowSums(rets,na.rm = TRUE)),1)
  ret[i]=rets
}
ret
[1]  0.3222529  0.1435537 -0.3998603 -2.1293011

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM