Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a limit for the possible number of nested ifelse statements

Tags:

r

if-statement

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.

like image 862
Yevgeny Tkach Avatar asked Jul 31 '14 15:07

Yevgeny Tkach


People also ask

What is the maximum number of nested CALL statements allowed?

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.

Is there a limit to if statements?

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.

How do you avoid multiple nested if statements?

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


1 Answers

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
like image 151
MrFlick Avatar answered Oct 07 '22 01:10

MrFlick