62571

Cumulative multiplication in R with the addition of extra constants

Question:

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

Any help would be greatly appreciated.

Answer1:

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

Answer2:

Using only base R define an anonymous function to embody the iteration and then run it using Reduce:

transform(DF, Z = Reduce(f = function(prev, i) (prev + Y[i]) * X[i], x = seq_along(X), init = 0, acc = TRUE)[-1])

giving (for the input in the Note at the end):

X Y Z 1 1 101 101 2 2 102 406 3 3 203 1827 4 4 104 7724 <h2>Added</h2>

The gsubfn function allows short forms for function definitions and using that we could rewrite the above as:

library(gsubfn) transform(DF, Z = fn$Reduce(f = prev + i ~ (prev + Y[i]) * X[i], x = seq_along(X), init = 0, acc = TRUE)[-1]) <h2>Note</h2>

We used the following input:

DF <- data.frame(X = 1:4, Y = 101:104)

Answer3:

I believe a good old fashioned for loop is the best way to solve this.

dat <- data.frame(Variable_X = 1:10, Variable_Y = 11:20) dat$Variable_Z <- dat$Variable_X[1]*dat$Variable_Y[1] for(i in seq_len(nrow(dat))[-1]){ dat$Variable_Z[i] <- (dat$Variable_Z[i - 1] + dat$Variable_Y[i])*dat$Variable_X[i] } dat # Variable_X Variable_Y Variable_Z #1 1 11 11 #2 2 12 46 #3 3 13 177 #4 4 14 764 #5 5 15 3895 #6 6 16 23466 #7 7 17 164381 #8 8 18 1315192 #9 9 19 11836899 #10 10 20 118369190

Recommend

  • Fatal error for
  • Rcpp programming efficiency
  • R: count the number of unique characters in that string
  • QR decomposition in RcppArmadillo
  • Output from sorted array with SimpleXML, xsort and xpath in PHP
  • Algorithm for solving simultaneous equations [closed]
  • loop_apply.o: file not recognized: File format not recognized
  • RcppEigen sparse matrix insert operation gives invalid class “dgCMatrix” error
  • How do I call the Pie function?
  • Satisfiablity checking in non-linear integer arithmetic by approximation
  • Implementing Karatsuba Multiplication in javascript?
  • Multiply all columns of one matrix by another matrix with bsxfun
  • Check if coordinate in selected area
  • d3.js create stacked bar chart from values in object
  • Webdriver kicks the bucket on “find_element”
  • Add new accepted protocol to URL/link validation in SharePoint 2010
  • Java Spring Jackson json library returning unicode instead of text
  • LDA: Why sampling for inference of a new document?
  • Dynamic SQL with variables inside a view (SQL Server)
  • Why do I link my jquery inside a document.write?
  • Multiplying column elements of sparse Matrix
  • SMT prover yields 'unknown' despite strong proven assertions
  • Jquery Ajax form using .on(“submit”,
  • How to add a “using” statement to the System.Data.Entity namespace [closed]
  • Applescript to ping test each client prior to ssh connection
  • How To Delete All Words After X Characters
  • No rows to manipulate in html table created with jQuery csvToTable?
  • FragmentActivity with a Fragment Containing a MapView
  • Adding independent aspx/asmx pages into DotNetNuke
  • xtable - background colour of added rows
  • Find group of records that match multiple values
  • Center align outputs in ipython notebook
  • Custom Tabgroup Appcelerator
  • Combining SpatialPolygonsDataFrame of two neighbour countries
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • Projection media query: browser support and workarounds?
  • Different response to non-authenticated users and AJAX calls
  • Does CUDA 5 support STL or THRUST inside the device code?
  • Why winpcap requires both .lib and .dll to run?
  • reshape alternating columns in less time and using less memory