假设您具有以下功能foo.当我运行一个for循环时,我希望它foo在foo最初返回值时跳过余数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))
}
Run Code Online (Sandbox Code Playgroud)
不可否认,我的R知识很少,而且这是干编码的,但以下内容应该有效:
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)
}
Run Code Online (Sandbox Code Playgroud)
编辑:更新后检查后代
作为编码实践的问题,不要这样做。拥有一个只能在特定循环内使用的函数并不是一个好主意。作为教育兴趣的问题,您可以评估家长环境中的“中断”。
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))
}
Run Code Online (Sandbox Code Playgroud)