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

u5rb5r59  于 2024-01-03  发布在  其他
关注(0)|答案(2)|浏览(177)

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

  1. > x
  2. 0.5 0.1
  3. 0.2 0.3
  4. > ind <- (x < 0.4)
  5. FALSE TRUE
  6. TRUE TRUE
  7. > output <- apply(ind, 2, &)
  8. FALSE TRUE

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

drkbr07n

drkbr07n1#

  1. y <- x < 0.4
  2. #efficient implementation
  3. matrixStats::colProds(y)
  4. #[1] 0 1
  5. #using apply
  6. apply(y, 2, prod)
  7. #[1] 0 1
  8. #or if & is just an example of a binary operator/function
  9. +Reduce(`&`, asplit(y, 1))
  10. #[1] 0 1

字符串

wqsoz72f

wqsoz72f2#

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

  1. library(matrixStats) # `colAlls`, `colProds`, and colMaxs
  2. library(Rfast) # `colAll` and `colprods`
  3. # de-conflict matrixStats::colMaxs and Rfast::colMaxs
  4. msColMaxs <- matrixStats::colMaxs
  5. set.seed(732506156)
  6. x <- matrix(runif(1e6), 10, 1e5)
  7. microbenchmark::microbenchmark(
  8. # base functions
  9. apply_and = as.logical(apply(x < 0.9, 2, prod)),
  10. apply_all = apply(x < 0.9, 2, all),
  11. colSum = colSums(x < 0.9) == nrow(x),
  12. Reduce = c(Reduce(`&`, asplit(x < 0.9, 1))),
  13. # matrixStats
  14. colAlls = colAlls(x < 0.9, value = TRUE),
  15. colProds = as.logical(colProds(x < 0.9)),
  16. msColMaxs = msColMaxs(x) < 0.9,
  17. # Rfast
  18. colAll = colAll(x < 0.9),
  19. #colAll_par = colAll(x < 0.9, parallel = TRUE), # not equivalent--bug!!
  20. colMaxs = colMaxs(x, TRUE) < 0.9,
  21. colMaxs_par = colMaxs(x, TRUE, TRUE) < 0.9,
  22. # check equivalency
  23. check = "identical",
  24. unit = "relative"
  25. )

字符串
结果如下:

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

展开查看全部

相关问题