【问题标题】:Compute all possible slopes between two points计算两点之间所有可能的斜率
【发布时间】:2018-09-03 15:25:34
【问题描述】:

我有两个向量

x <- rnorm(100)
y <- rnorm(100)

我需要计算所有点之间的斜率(公式:y2 - y1/ x2 - x1)。所以我需要(x1, y1)(x1, y2)(x1, y1)(x1, y3)...、(x2,y2)和(y2,y3)等点之间的斜率。总共是choose(n, 2)斜率。

如何在 R 中高效地做到这一点(我需要运行多次,所以效率在这里非常重要)

【问题讨论】:

    标签: r performance


    【解决方案1】:

    如果您需要choose(n, 2) 之间的n 斜率(x, y) 点数,请使用

    xy <- cbind(x, y)
    library(RcppAlgos)
    ind <- comboGeneral(nrow(xy), 2)
    d <- xy[ind[, 2], ] - xy[ind[, 1], ]
    slope <- d[, 2] / d[, 1]
    

    我没有使用 R 核心的 combn 函数。有关案例研究,请参阅 Product between all combinations of a vector's elements

    【讨论】:

      【解决方案2】:

      使用最后注释中的数据并假设需要选择 2 个斜率。

      slopes <- c(combn(y, 2, diff) / combn(x, 2, diff))
      slopes
      ## [1] -3.7970202 -1.4062612 -3.8066222 -3.1325626 -0.9648338 -3.8171698
      ## [7] -2.5220191 -0.3885287 -0.5732387  4.1033272
      

      这些分别是这些对的斜率:

      nms <- combn(n, 2, paste, collapse = ":")
      nms
      ## [1] "1:2" "1:3" "1:4" "1:5" "2:3" "2:4" "2:5" "3:4" "3:5" "4:5"
      
      all.equal(slopes, slopes2[order(nms2)])
      

      添加

      如果这还不够快,请尝试使用 gRBase(在 Bioconductor 中)的combnPrim

      library(gRBase)
      
      xx <- combnPrim(x, 2)
      yy <- combnPrim(y, 2)
      slopes2 <- (yy[2, ] - yy[1, ]) / (xx[2, ] - xx[1, ])
      slopes2
      ## [1] -3.7970202 -1.4062612 -0.9648338 -3.8066222 -3.8171698 -0.3885287
      ## [7] -3.1325626 -2.5220191 -0.5732387  4.1033272
      
      nms2 <- apply(combnPrim(n, 2), 2, paste, collapse = ":")
      ## [1] "1:2" "1:3" "2:3" "1:4" "2:4" "3:4" "1:5" "2:5" "3:5" "4:5"
      
      all.equal(slopes, slopes2[order(nms2)])
      ## [1] TRUE
      

      注意

      我们使用以下输入:

      set.seed(123)
      n <- 5
      x <- rnorm(n)
      y <- rnorm(n)
      

      【讨论】:

        猜你喜欢
        • 2011-03-22
        • 2019-03-23
        • 2015-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-11
        • 2017-05-02
        相关资源
        最近更新 更多