代码之家  ›  专栏  ›  技术社区  ›  andrewj

在R中的for循环内运行函数时中断for循环

  •  8
  • andrewj  · 技术社区  · 16 年前

    foo . 当我经营一家 for 循环,我想跳过剩下的部分 福 什么时候 福 最初返回 0 break 当它在函数中时不起作用。

    no loop to break from, jumping to top level .

    有什么建议吗?

    foo <- function(x) {
        y <- x-2
        if (y==0) {break} # how do I tell the for loop to skip this
        z <- y + 100
        z
    }
    
    
    for (i in 1:3) {
        print(foo(i))
    }
    
    5 回复  |  直到 14 年前
        1
  •  7
  •   Dusty    16 年前

    foo <- function(x) {
        y <- x-2
        if (y==0) {return(NULL)} # return NULL then check for it
        z <- y + 100
        z
    }
    
    for (i in 1:3) {
        j <- foo(i)
        if(is.null(j)) {break}
        print(j)
    }
    

    编辑:更新了后代的空检查

        2
  •  4
  •   Ian Fellows    16 年前

    作为一种编码实践,不要这样做。拥有一个只能在特定循环中使用的函数不是一个好主意。出于教育兴趣,你可以评估家长环境中的“休息”。

    foo <- function(x) {
        y <- x-2
        if (y==0) {eval.parent(parse(text="break"),1)} 
        z <- y + 100
        z
    }
    
    
    
    for (i in 0:3) {
        print(foo(i))
    }
    
        3
  •  4
  •   William Doane    16 年前

    我们可以更具创造性一点吗?你能重述你的问题,以利用以下方法,其中的操作是基于向量的优势?

    x <- 1:3  
    y <- x[x-2 < 0] - 2 + 100 # I'm leaving the "- 2" separate to highlight the parallel to your code  
    y  
    

    foo <- function(x) {
      y <- x - 2
      if (y != 0) {
        z <- y + 100
        z
      } # else implicitly return value is NULL
    }
    
    for (i in 1:3) {
      if (is.numeric(result <- foo(i))) {
        print(result)
      } else {
        break 
      }
    }
    
        4
  •  2
  •   Leo Alekseyev    16 年前

    另一种方法是抛出错误并用 try

    foo <- function(x) {
        y <- x-2
        if (y==0) {stop("y==0")} 
        z <- y + 100
        z
    }
    
    try(for (i in 0:5) {
           print(foo(i))
    }, silent=TRUE)
    
    ## or use tryCatch:
    for (i in 0:5) {
       bar <- tryCatch(foo(i),error=function(e) NA)
       if(is.na(bar)){ break } else { print(bar) }
    }
    
        5
  •  0
  •   Kelsey    16 年前

    我不知道怎么做 r 但我发现这个问题很有趣,因为我可以查找一种新语言的语法,所以如果我的答案完全错误,请原谅:)

    foo <- function(x) { 
        y <- x-2 
        if (y!=0) z <- NULL else z <- y + 100 
        z 
    }
    
    
    for (i in 1:3)
    { 
        a <- foo(i)
        if (a == NULL) {next}
        print(a)
    }