簡體   English   中英

更高效的R功能,可累積先前的結果

[英]More efficient R function that accumulate the prior result

我有兩個數據幀,如下所示:

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 ...
...

我想乘以totPrimas的第一行* a的第一行。 totPrimas [1,] * a [1,]加上totPrimas [2,]的結果我想乘以a [2,],依此類推。

我寫了一個函數但是很慢,實際數據幀是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)

感謝您的幫助。 謝謝

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")

代碼的結果:

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

讓我們對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;
}

(如果使用RStudio,則可以簡單地創建一個新的“ C ++文件”,將代碼復制到其中,然后單擊“源”。當然,您需要安裝Rcpp軟件包,如果使用Windows,則需要Rtools。)

然后在R中,您可以像這樣遍歷各列:

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

讀者練習:

  1. 循環瀏覽Rcpp中的列。
  2. 使用遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM