获取contextstack溢出错误-for循环中嵌套的ifelse语句过多? [英] Getting contextstack overflow error - too many nested ifelse statements within for loop?

查看:107
本文介绍了获取contextstack溢出错误-for循环中嵌套的ifelse语句过多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个for循环,它遍历每行,检查行(下一行和当前行)之间以及同一行内是否存在多个条件.我收到一个错误:contextstack溢出. 我有一堆嵌套的ifelse语句(太多),想知道当有很多可能的条件组合要检查时,人们如何减少使用的ifelse语句的数量.您是否将其分解为多个循环? 我看到一些方法可以将日期划分为多个分组,并在分组中包含ifelse语句(因此,这是否是嵌套ifelse语句的if语句?),但是我不确定这是否可以帮助我摆脱错误越来越.

I currently have a for loop that iterates over each row checking for multiple conditions being true between rows (the next and current row) and within the same row. I am getting an Error: contextstack overflow. I have a bunch of nested ifelse statements (too many) and was wondering how people reduce the number of ifelse statements they use when there are a lot of possible combinations of conditions to check. Do you break this up into multiple loops? I see a few ways where I can segment the date into groupings and have ifelse statements within the groupings (so would this be an if statement with ifelse statements nested?) but I am not sure if that will help me get rid of the error I am getting.

for (i in 1 : length(df$id)-1){ ifelse(many conditions, do this, ifelse(many conditions, do this,    ifelse(many conditions, do this, ...... ifelse(many conditions, do this, xxxxx) }

因此,我实际上是在每一行上进行迭代,因为我需要在每一行内与上一行进行比较.主要问题是我似乎达到了允许嵌套的ifelse语句的最大数量.有没有一种方法可以更好地将其分组以减少该限制因素,因为现在我的全部都是嵌套的.我可以有5条if语句(我的多个条件之一实际上是5级类别),然后将ifelse语句嵌套在具有其他条件的语句中,这样循环就不会评估每个ifelse语句了吗?在R中可行吗?

So I am essentially iterating over each row because I need to compare within each row and against the previous row. The main problem is I seem to reach the maximum number of ifelse statements allowed to be nested. Is there a way to better group this to reduce that limiting factor because right now mine are all nested. Can I have 5 if statements (one of my many criteria is actually a 5 level cateogry) and then nest ifelse statements within those with other criteria so the loop does not evaluate every ifelse statement? Is that viable in R?

推荐答案

如果是分类表,请使用查找表:

Use a lookup table if it's categorical:

> df = data.frame(x=1:5, y=letters[1:5])
> df
  x y
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e

> z=c("a", "c", "d")

缓慢的嵌套方式:

> ifelse(z == "a", 1, ifelse(z=="b", 2, ifelse(z=="c", 3, ifelse(z=="d", 4,ifelse(z=="e", 5, NA)))))
[1] 1 3 4

更快的R方式:

> df$x[sapply(z, function(x) which(x==df$y))]
[1] 1 3 4

如果是数字,则可以改用cut:

If it's numeric, you can use cut instead:

> z = c(1.1, 2.23)
> df$y[cut(z, df$x)]
[1] a b

这篇关于获取contextstack溢出错误-for循环中嵌套的ifelse语句过多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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