如果你有兴趣,可以去掉for循环,一步完成。
wh <- which(as.matrix(factor_perms), arr.ind = TRUE)
factors <- split(all_factors[wh[,2]], wh[,1])
head(factors)
# $`2`
# [1] "f6"
# $`3`
# [1] "f5"
# $`4`
# [1] "f5" "f6"
# $`5`
# [1] "f4"
# $`6`
# [1] "f4" "f6"
# $`7`
# [1] "f4" "f5"
请注意,虽然wh 是列优先的,但
head(wh)
# row col
# [1,] 33 1
# [2,] 34 1
# [3,] 35 1
# [4,] 36 1
# [5,] 37 1
# [6,] 38 1
split 步骤根据不同的 row 值对其输出进行排序,因此它按行排序。
它的价值取决于您的需求:根据您对 R 的舒适度,一个可能比另一个更容易阅读(因此维护);并且这个非for 循环(使用此数据)是另一个循环的 60 倍。诚然,在需要几微秒的时间内分析代码是一种浪费时间的愚蠢(低效)方式,但如果您的数据大得多,这可能会有优势。
expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory time gc
<bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> <list> <list>
1 r2 116.3us 125.8us 6670. 22.26KB 4.44 3003 2 450ms <NULL> <Rprofmem[~ <bch:tm~ <tibble~
2 ThomasIsCoding 8.46ms 8.95ms 109. 1.02MB 2.09 52 1 478ms <NULL> <Rprofmem[~ <bch:tm~ <tibble~