当在R中的for循环中运行一个函数时,会跳出for循环 [英] breaking out of for loop when running a function inside a for loop in R

查看:833
本文介绍了当在R中的for循环中运行一个函数时,会跳出for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有以下函数 foo 。当我为循环运行时,我希望在<$ c>时跳过 foo 的其余部分$ c> foo 最初返回 0 的值。但是, break 在函数内部不起作用。

现在写入,我得到一个错误消息,没有循环打破,跳到顶层



有什么建议?

  foo < -  function(x) {
y< - x-2
if(y == 0){break}#如何告诉for循环跳过
z< - y + 100
z


$ b $(b在1:3中){
print(foo(i))
}

$ b $

  foo < -  function(x){
y < - x-2
if(y == 0){return(NULL)}#return NULL然后检查它
z< -y + 100
z
}

for(i in 1: 3){
j < - foo(i)
if(is.null(j)){break}
print(j)
}


$编辑:更新后检查后代


Suppose you have the following function foo. When I'm running a for loop, I'd like it to skip the remainder of foo when foo initially returns the value of 0. However, break doesn't work when it's inside a function.

As it's currently written, I get an error message, no loop to break from, jumping to top level.

Any suggestions?

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))
}

解决方案

Admittedly my R knowledge is sparse and this is drycoded, but something like the following should work:

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)
}

Edit: updated null check for posterity

这篇关于当在R中的for循环中运行一个函数时,会跳出for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆