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
406 views
in Technique[技术] by (71.8m points)

r - Getting contextstack overflow error - too many nested ifelse statements within for loop?

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

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

The slow nested way:

> 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

The faster R way:

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

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

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

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

...