跳出内循环
我试图将一个循环嵌套在另一个循环中,并在满足条件时跳出内循环并继续外循环。我的数据帧 a_2011
和 TRS
具有以下形式:
a_2011<- data.frame(c("10N11W11", "10N11W11", "10N12W7", "10N13W22" , "10N14W1"))
TRS <- data.frame(c("10N12W7","10N13W22","10N14W1", "10N15W33"))
for (i in 1:nrow(a_2011))
{
a_2011$City[i] <- 1
for (j in 1:nrow(TRS))
{
if ( as.character(a_2011[i,1]) == as.character(TRS[j,1]) )
{
break
}
else
{
a_2011$City[i] <- 0
}
}
}
a_2011$City
的所需输出是由 2 个 0 后跟 3 个 1 组成的列向量。但上面的代码并没有跳过内循环中break语句之后的命令。
如果您能帮助找出这里的问题,我们将不胜感激。
I am trying to nest one loop in another and break out of the inner loop and move on with the outer loop when a condition is met. My dataframes a_2011
and TRS
are of the following form:
a_2011<- data.frame(c("10N11W11", "10N11W11", "10N12W7", "10N13W22" , "10N14W1"))
TRS <- data.frame(c("10N12W7","10N13W22","10N14W1", "10N15W33"))
for (i in 1:nrow(a_2011))
{
a_2011$City[i] <- 1
for (j in 1:nrow(TRS))
{
if ( as.character(a_2011[i,1]) == as.character(TRS[j,1]) )
{
break
}
else
{
a_2011$City[i] <- 0
}
}
}
The desired output for a_2011$City
is a column vector of 2 zeros followed by 3 ones. But the code above is not skipping the commands after the break statement in the inner loop.
Would appreciate any help in figuring out what is wrong here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题在于,只有当 TRS 的第一行匹配时,内部循环才会中断。为了使你的代码工作,你必须这样做:
你可以像这样删除对内部循环的需要:
..然后为了进一步简化它,你也可以删除外部循环:
The problem is that the inner loop only breaks if the first row of TRS matches. To make your code work you'd have to do like this:
You can remove the need for the inner loop like this:
..And then to simplify it further, you can remove the outer loop too:
在 R 中不需要循环来实现这一点。
You don't need a loop to achieve this in R.
你根本不需要循环。这就是
ifelse
的用途。You don't need a loop at all. This is what
ifelse
is for.