【问题标题】:How can I get a max value of each column in matrix using For Loop in R如何使用 R 中的 For 循环获取矩阵中每一列的最大值
【发布时间】:2017-07-24 08:26:46
【问题描述】:

例如:如果我有这个矩阵并且我想使用 for 循环计算每列的最大值我应该怎么做

X = 矩阵 (1:12, nrow = 4, ncol=3)

【问题讨论】:

    标签: loops for-loop matrix max multiple-columns


    【解决方案1】:

    这可以通过使用如图所示的 ncol() 和 max() 函数来完成。一旦获得了列索引号,就可以提取相应的行,如下所示:

    X = matrix (1:12, nrow = 4, ncol=3)
    #Let soln be the solution vector that stores the corresponding maximum value of each column              
    soln=c()
    
    #Traverse the matrix column-wise
    for (i in 1:ncol(X))
    {
      #Extract all rows of the ith column and find the maxiumum value in the same column
      soln[i]= max(X[,i])
      print(soln[i])
    }
    
    #Print the solution as a vector
    soln
    

    此外,here 也回答了一个类似的问题,但没有使用 for 循环(通过使用 apply() 函数)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-31
      • 2016-07-09
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2017-09-29
      相关资源
      最近更新 更多