I wrote a code that uses 75(!!!) nested ifelse statements.
I know its probably the most inefficient code I could write, but when I tried to run it I received the following error:
>Error: unexpected ')' in:
" ifelse(basic$SEMType=="ppc" &
(grepl("Wellpoint Prospecting",basic$CategoryName)), "Wellpoint Prospecting","other"
)))))))))))))))))))))))))))))))))))))"
I checked and doubled checked the number of ")". Its correct and the ifelse closes.
I also tried to run the nested ifelse by chunks, 15 at a time (and sometimes bigger chunks) and it works, so I figured the chance for syntax error is low.
Has anyone ever encountered such limitations?
I now run the code piece wise the inner ifelse first and record the result and move up the channel. This seems to work so far.
There is no virtual limit in nesting if-else statements. But every time you call a function, the CPU has to save the current state in the stack.
In normal circumstances, Excel places a limit on the number of nested conditional formulas that you can use. The limit is 7. However, it is possible to circumvent the limitation over the number of nested conditional formulas by cascading them.
Avoid using nested if-else statements. Keep the code linear and straightforward. Utilize creating functions/methods. Compare it when we try to use an if-else statement that is nested and that does not utilize the power of the return statement, We get this (Code 1.4).
At least with this method, I seem to be able to create at most 50 levels of nesting
x<-"NA"
for(i in 1:50) {
x<-paste0("ifelse(x==",i,",",i,",", x, ")")
}
x
eval(parse(text=x), list2env(list(x=21)))
But if i try 51, i get the error
Error in parse(text = x) : contextstack overflow at line 1
so maybe that is specific to parse. It seems odd that you would get a syntax error.
Thanks to the link provided by @shadow, Brian Ripley confirmed this in a 2008 response to an r-help question
In this particular case [contextstack overflow], it is saying that you have more than 50 nested parse contexts
And @Spacedman found where this limit is defined in the R source code
#define CONTEXTSTACK_SIZE 50
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With