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



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

i have loop iterates on each row checking multiple conditions beingness true between rows (the next , current row) , within same row. getting error: contextstack overflow. have bunch of nested ifelse statements (too many) , wondering how people cut down number of ifelse statements utilize when there lot of possible combinations of conditions check. break multiple loops? see few ways can segment date groupings , have ifelse statements within groupings (so if statement ifelse statements nested?) not sure if help me rid of error getting.

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

so iterating on each row because need compare within each row , against previous row. main problem seem reach maximum number of ifelse statements allowed nested. there way improve grouping cut down limiting factor because right mine nested. can have 5 if statements (one of many criteria 5 level cateogry) , nest ifelse statements within other criteria loop not evaluate every ifelse statement? viable in r?

use lookup table if it's categorical:

> df = data.frame(x=1:5, y=letters[1:5]) > df x y 1 1 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, can utilize cut instead:

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

r if-statement for-loop

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -