简体   繁体   中英

More efficient R function that accumulate the prior result

I have two data frames as follow:

totPrimas:

54 54 54 ...
54 56 55 ...
54 56 55 ...
...

and a:

0.998 0.988 0.958 ...
0.997 0.978 0.958 ...
0.995 0.878 0.948 ...
...

I want to multiply the first row of totPrimas * first row of a. The result of totPrimas[1,]* a[1,] plus totPrimas[2,] I want to multiply for a[2,] and so on.

I wrote a function but is to slow, the real data frame is 564, 20000.

b<- matrix(0, nrow = 10, ncol = 10)
b<- as.data.frame(b)


        prova3 <- function(i){

        if(i==1){
        b[1,] <<- totPrimas[i,]*a[i,]

        }else{

        b[i,] <<- (b[i-1,] + totPrimas[i,])*a[i,]
        }

        }

    sapply(1:10, prova3)

I will appreciate your help. Thanks

totPrimas <- read.table(text = "54 54 54
54 56 55
54 56 55")

a <- read.table(text = "0.998 0.988 0.958
0.997 0.978 0.958
0.995 0.878 0.948")

Result from your code:

#   [,1]   [,2]     [,3]    
#V1 53.892 107.5683 160.7605
#V2 53.352 106.9463 143.0668
#V3 51.732 102.2493 149.0723

Let's make a trivial translation to Rcpp:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector fun(const NumericVector x, const NumericVector y) {
  NumericVector z(x.size());
  z(0) = x(0) * y(0);
   for(int i = 1; i < x.size(); i++) {
     z(i) = (z(i-1) + x(i)) * y(i);
   }
   return z;
}

(If you use RStudio, you can simply create a new "C++ File", copy the code into it, and click "Source". Of course you need to install the Rcpp package and, if you use Windows, you need Rtools.)

Then in R, you can loop over the columns like this:

t(mapply(fun, x = totPrimas, y = a))
#     [,1]     [,2]     [,3]
#V1 53.892 107.5683 160.7605
#V2 53.352 106.9463 143.0668
#V3 51.732 102.2493 149.0723

Exercises for the reader:

  1. Loop over the columns in Rcpp.
  2. Use recursion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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