【问题标题】:Create a Function and Find the Largest Value in the Dataset and Find its Position of Row and Column using an IF statement & a Loop [closed]创建一个函数并在数据集中查找最大值,并使用 IF 语句和循环查找其在行和列的位置 [关闭]
【发布时间】:2016-10-10 04:14:23
【问题描述】:

我需要创建一个名为 max.mat() 的函数,并使用该函数来识别与数据集的最大值关联的矩阵中的位置(行和列)。有人告诉我要创建这个函数,我应该使用两件事:1)“if 语句”2)循环

【问题讨论】:

  • 阅读以下文档:?matrix 创建测试矩阵,?for 运行 for 循环,if 构建 if 语句。构建矩阵后,请阅读help("[") 以了解如何访问矩阵的元素。这应该足以让您入门。
  • 是否需要使用IF语句和Loop?因为您可以使用其他功能轻松做到这一点...或实际功能...
  • 无需过多介绍。切入正题,最重要的是,提供一个小型数据集。应该使用dput 模拟或使用它以及您尝试的代码。总是欢迎以任何形式、形式或大小表现出一些努力。
  • 嗨,Stacie,欢迎来到 Stack Overflow!请务必查看How to Ask a Good Question,了解如何改进此问题及其在此处的接收情况。

标签: r


【解决方案1】:

如果您真的需要使用 for 循环和 if 语句,这是一种方法。但首先让我们用一堆随机数创建一个矩阵。

set.seed(100)
mymat <- matrix(runif(100), ncol = 10, nrow = 10)

现在,我们创建函数。

max.mat <- function(x){
  # iterate through the columns from 1 to the max number
  # of columns
for(i in 1:ncol(x)){
  # iterate through each number in a column
  for(j in 1:nrow(x)){
    # if the jth number in the ith column equals the maximum
    # value of x
    if(x[j,i] == max(x)){
      # return a vector that says what j and i are
      return(c("row" = j, "col" = i))
      # then stop looping through stuff
      stop()
      }
    }
  }
}

max.mat(mymat)
     row col
[1,]   9   4

这使用了两个 for 循环。如果需要,我们可以将其简化为一个,但我们也可以不使用循环

max.mat.easier <- function(x){
  which(x == max(x), arr.ind = TRUE)
}

max.mat.easier(mymat)
     row col
[1,]   9   4

【讨论】:

  • 如果您还需要获取最大值,您应该也可以编辑此代码以将其返回。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2021-08-21
  • 2022-01-03
  • 1970-01-01
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多