繁体   English   中英

获得两个值之间成对最大值的矩阵的有效方法

[英]Efficient way to obtain matrix with pairwise maximum between two values

我想创建一个矩阵,该矩阵对于条目i,j返回D[i,1]D[j,1]之间的最大值。

我有一个数字向量,可以将MWE中的数字简化为:

set.seed(10)
n <- 2000 
D <- matrix(runif(n,0,100), ncol=1)

Base R中使用double for循环,效率极低:

X <- Matrix::Matrix(0, nrow = n, ncol = n, sparse = T)

for (i in 1:n) {
  for (j in 1:n) {
    X[i,j] <- max(D[i,1], D[j,1])
  }
}

我也尝试过dplyr

library(dplyr)

X <- tibble(i = 1:n, D = D)

X <- expand.grid(i = 1:n, j = 1:n)

X <- X %>%
  as_tibble() %>%
  left_join(X, by = "i") %>%
  left_join(X, by = c("j" = "i")) %>%
  rowwise() %>%
  mutate(D = max(D.x, D.y)) %>%
  ungroup()

它会返回Error: std::bad_alloc然后我才能执行X <- Matrix::Matrix(X$D, nrow = n, ncol = n, sparse = T)

我的最后尝试是在Windows下也可以使用RcppArmadillo

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;

// [[Rcpp::export]]
arma::mat pairwise_max(arma::mat x, arma::mat y) {
  // Constants
  int n = (int) x.n_rows;

  // Output
  arma::mat z(n,n);

  // Filling with ones
  z.ones();

  for (int i=0; i<n; i++)
    for (int j=0; j<=i; j++) {
      // Fill the lower part
      z.at(i,j) = std::max(y(i,0), y(j,0));
      // Fill the upper part
      z.at(j,i) = z.at(i,j);
    }

    return z;
}

它几乎可以完美地工作,但是我很确定我没有看到使用base R的有效方法。

在基数R中,我会做

D2 <- drop(D)
X2 <- outer(D2, D2, pmax)

这是double for循环的约20倍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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