R中的累加和额外常数 [英] Cumulative multiplication in R with the addition of extra constants

查看:45
本文介绍了R中的累加和额外常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R的新手,并在以下累加乘法与额外常量的结合中苦苦挣扎.我希望在数据框中实现以下目标:

I'm new to R and struggling with the following combination of cumulative multiplication with the addition of extra constants. I'm looking to achieve the following in a dataframe:

Variable_X         Variable_Y           Variable_Z
X1                 Y1                   Y1*X1      = Z1 
X2                 Y2                   (Z1+Y2)*X2 = Z2 
X3                 Y3                   (Z2+Y3)*X3 = Z3
X4                 Y4                   (Z3+Y4)*X4 = Z4

任何帮助将不胜感激.

推荐答案

library(Rcpp)

cppFunction("NumericVector foo_cpp (NumericVector x, NumericVector y) {
  int n = x.size(), i;
  NumericVector z(n);
  double tmp = 0.0;
  for (i = 0; i < n; i++) {
    tmp = (tmp + y[i]) * x[i];
    z[i] = tmp;
    }
  return z;
  }")

set.seed(0)
dat <- data.frame(x = runif(1e+6), y = runif(1e+6))
system.time(z <- foo_cpp(dat$x, dat$y))
#   user  system elapsed 
#  0.016   0.000   0.014 
dat$z <- z

这篇关于R中的累加和额外常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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