【问题标题】:My for loop in r stops at the first iteration [duplicate]我在 r 中的 for 循环在第一次迭代时停止 [重复]
【发布时间】:2019-12-17 03:33:49
【问题描述】:

我在 r 中有一个数据框,我想提供每个整数变量的箱线图。我有 34 个变量,因此手动执行它们是没有用的,因此我选择了 for 循环,但它只返回第一个变量的第一个箱线图。 这是我使用的代码:

for (i in 1:34) {
  if (class(data[,i])== "integer") {
    return(boxplot(data[,i])) 
  } 
}

【问题讨论】:

    标签: r loops for-loop


    【解决方案1】:

    您的代码停止,因为调用了return

    遗憾的是,在 R 中,如果不使用 additional libraries,就无法将基础图存储在变量中。但是如果你使用 ggplot2 来创建你的箱线图,你可以将它们存储到一个列表中:

    plots <- list()
    a <- 1
    for (i in 1:34) {
      if (class(data[,i]) == "integer") {
        plots[[a]] <- boxplot(data[,i])) 
        a <- a + 1
      } 
    }
    

    随后,您可以使用 ggplot2 中的 grid.arrange 将它们全部绘制在一个网格中。下面的代码应该可以解决问题(非常感谢Josh O'Brien):

    library(gridExtra)
    
    n <- length(plots)
    nCol <- floor(sqrt(n))
    do.call("grid.arrange", c(plots, ncol=nCol))
    

    【讨论】:

      【解决方案2】:

      详细说明georg_un的回答:

      调用return() 将停止所有循环的执行。

      考虑这个例子:

      for (i in 1:500) {
      
        for (y in 1000:1) {
      
            cat(paste("big", i, "small", y))
      
            return("the end is nigh!")
        }
      
      } 
      

      这不会打印 500 000 个项目(500x 大循环,1000x 小循环),而只会打印一个。
      return() 将停止一切...

      return 通常不用于 for 循环的上下文中,而是用于函数的提前终止。

      【讨论】:

        猜你喜欢
        • 2012-03-05
        • 1970-01-01
        • 1970-01-01
        • 2021-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-02
        • 2019-06-05
        相关资源
        最近更新 更多