gpt4 book ai didi

r - 在 R 中必要时矩阵未填充 1

转载 作者:行者123 更新时间:2023-12-04 08:51:14 27 4
gpt4 key购买 nike

我正在尝试用 (1) 填充矩阵,其中索引对应于相同维度的另一个矩阵的最大值。
下面是一个可重现的例子

set.seed(1)
matric <- matrix(rnorm(3000), nrow = 500, ncol = 6)

best <- matrix(0, nrow = 500, ncol = 6)
n_end <- 500

for (i in n_end) {
best[which(matric[i,] == max(matric[i,]))] <- 1
}
## the best model has the higher sum
best1 <- colSums(best)
请帮忙!! :)

最佳答案

我们可以使用 seq_len1:n_end在循环内部,当我们分配给“最佳”的同一行时,也对该矩阵进行索引

for(i in 1:n_end) {
best[i,][matric[i,] == max(matric[i,])] <- 1
}

或者如果每行只有一个最大值,则使用 max.col因为它更快且矢量化
best[cbind(seq_len(nrow(best)), max.col(matric, 'first'))] <- 1

或与 rowMaxs来自 matrixStats
library(matrixStats)
+(matric == rowMaxs(matric))

关于r - 在 R 中必要时矩阵未填充 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64093232/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com