如何首先将R数值矩阵转换为布尔矩阵,然后在该布尔矩阵的列之间应用合取运算符?

u5rb5r59  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(131)

如何首先将R数值矩阵转换为布尔矩阵,然后在该布尔矩阵的列之间应用合取运算符?例如:

> x
0.5 0.1
0.2 0.3

> ind <- (x < 0.4)
FALSE TRUE
TRUE TRUE

> output <- apply(ind, 2, &)
FALSE TRUE

字符串
这里我滥用apply,因为它似乎不这样工作。

drkbr07n

drkbr07n1#

y <- x < 0.4

#efficient implementation
matrixStats::colProds(y)
#[1] 0 1

#using apply
apply(y, 2, prod)
#[1] 0 1

#or if & is just an example of a binary operator/function
+Reduce(`&`, asplit(y, 1))
#[1] 0 1

字符串

wqsoz72f

wqsoz72f2#

对几种不同的选择进行基准测试:

library(matrixStats) # `colAlls`, `colProds`, and colMaxs
library(Rfast) # `colAll` and `colprods`

# de-conflict matrixStats::colMaxs and Rfast::colMaxs
msColMaxs <- matrixStats::colMaxs

set.seed(732506156)
x <- matrix(runif(1e6), 10, 1e5)

microbenchmark::microbenchmark(
  # base functions
  apply_and = as.logical(apply(x < 0.9, 2, prod)),
  apply_all = apply(x < 0.9, 2, all),
  colSum = colSums(x < 0.9) == nrow(x),
  Reduce = c(Reduce(`&`, asplit(x < 0.9, 1))),
  # matrixStats
  colAlls = colAlls(x < 0.9, value = TRUE),
  colProds = as.logical(colProds(x < 0.9)),
  msColMaxs = msColMaxs(x) < 0.9,
  # Rfast
  colAll = colAll(x < 0.9),
  #colAll_par = colAll(x < 0.9, parallel = TRUE), # not equivalent--bug!!
  colMaxs = colMaxs(x, TRUE) < 0.9,
  colMaxs_par = colMaxs(x, TRUE, TRUE) < 0.9,
  # check equivalency
  check = "identical",
  unit = "relative"
)

字符串
结果如下:

#> Unit: relative
#>         expr        min         lq       mean     median         uq        max neval
#>    apply_and 146.516660 148.434487 103.863032 120.869415 120.209196 18.2836551   100
#>    apply_all 126.829494 126.492837  88.907218 102.277152  96.951077 21.3047345   100
#>       colSum   4.919272   4.923516   4.518798   3.929422   4.616963  5.3557266   100
#>       Reduce  18.801419  20.290610  18.742439  17.456448  18.347016 11.5879346   100
#>      colAlls   6.184698   6.122412   5.004275   4.889357   4.816862  4.8643490   100
#>     colProds 112.836076 118.907810  81.498059  95.937850  91.085323 14.3130057   100
#>    msColMaxs   5.617544   5.574937   3.968398   4.466546   4.135480  1.1644795   100
#>       colAll   4.685315   4.555185   4.189683   3.552234   3.351570  5.0080369   100
#>      colMaxs   3.353147   3.348960   2.280108   2.683182   2.431675  0.8313514   100
#>  colMaxs_par   1.000000   1.000000   1.000000   1.000000   1.000000  1.0000000   100

相关问题