Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...