簡體   English   中英

減少 R 中具有大向量的二元 ecdf 的計算時間

[英]Reduce computation time of bivariate ecdf with large vectors in R

我想計算兩個非常大的向量(超過 2.5 億個元素)的二元經驗累積密度 function,以使用 for 循環計算每對值 i:n 的百分比並將其存儲在結果向量中。 由於兩個向量的長度,很明顯計算時間會非常長,所以我想將我的 for 循環轉換為 rcpp。

# minimal working example

vec_a <- runif(1e+4)
vec_b <- rnorm(1e+4)
total <- length(vec_b)
store <- vector()

for(i in 1:total){store[i] <- sum(vec_a <= vec_a[i] & vec_b <= vec_b[i])/total}

我試圖翻譯我的循環,但由於我剛開始使用 rcpp,有些事情對我來說不是很清楚。 如果有人能給我一個答案,我會很高興 a.)為什么結果不一樣 b.)如果可以加快 rcpp 代碼的速度。

# Rcpp protoype
library(Rcpp)
cppFunction(
  "NumericVector FasterLoop(NumericVector x, NumericVector y) {
  const int n = x.length();
  NumericVector z(n);
  for (int i=0; i < n; ++i) {
   z[i] = sum(x <= x[i] & y <= y[i])/n;
  }
  return z;
}")

proto <- FasterLoop(vec_a, vec_b)

問題是sum(x <= x[i] & y <= y[i])返回一個 integer,然后sum(x <= x[i] & y <= y[i])/n執行一個integer划分。 您必須將sum(x <= x[i] & y <= y[i])轉換為double 這是通過z[i] = sum(x <= x[i] & y <= y[i])然后將z[i]除以n自動完成的。

library(Rcpp)
cppFunction(
  "NumericVector FasterLoop(NumericVector x, NumericVector y) {
  const int n = x.length();
  NumericVector z(n);
  for (int i=0; i < n; ++i) {
   z[i] = sum(x <= x[i] & y <= y[i]);
  }
  return z/n;
}")

FasterLoop(c(1,2,3), c(1,2,3))

暫無
暫無

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

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