【问题标题】:Return highest value in each row into 1 and make the rest of the numbers in row 0将每行中的最大值返回为 1,并将行中的其余数字设为 0
【发布时间】:2017-02-04 21:11:05
【问题描述】:

我有一个矩阵:

head(Y_hat)
         [,1]      [,2]      [,3]
40  0.8316621 0.7593911 0.7446870
56  0.8429158 0.6935900 0.7660440
85  0.8405038 0.6874243 0.7406380
134 0.7269549 0.7584314 0.7089962
30  0.7358268 0.6745820 0.6879305
131 0.7475585 0.7617574 0.7782455

我想写一个函数将每一行转换为0和1。每一行的最大值为1,其他两个值为0。例如,第40行将返回(1 0 0) .我该怎么做?

【问题讨论】:

  • mat == apply(mat, 1, max)
  • t(apply(Y_hat, 1, function(x) as.numeric(x == max(x))))
  • 这行得通。谢谢!

标签: r function matrix


【解决方案1】:

我们可以通过将每行的maxmatrixStats 中的rowMaxs 进行比较

library(matrixStats)
+(m1==rowMaxs(m1))
#    [,1] [,2] [,3]
#40     1    0    0
#56     1    0    0
#85     1    0    0
#134    0    1    0
#30     1    0    0
#131    0    0    1

或者 base R 选项是通过行/列索引 (max.col) 获得每行的最大值,然后进行比较

+(m1==m1[cbind(1:nrow(m1), max.col(m1))])

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2011-09-01
    相关资源
    最近更新 更多