how to increase the ifelse limit in R?

5

I need to calculate the years of study from the PNAD questionnaire.

I made a programming similar to this below, but I have many ifelse within the other (121 to be exact), because I have a larger chain of questions, but R does not calculate beyond 50 ifelse lines.

pnad2015$agua<-ifelse(v0211==1 & v0212==2, 0,
               ifelse (v0211==1 & v0212==4, 1,
               ifelse (v0211==1 & v0212==6, 1,
               ifelse (v0211==3 & v0213==1, 0,
               ifelse (v0211==3 & v0213==3, 1, NA)))))
    
asked by anonymous 05.12.2016 / 00:55

1 answer

4

One possible way is to use case_when of dplyr . I did some testing and did not find the limitation of many cases as ifelse has. In your case, it would look like this:

case_when(
  v0211==1 & v0212==2 ~ 0,
  v0211==1 & v0212==4 ~ 1,
  v0211==1 & v0212==6 ~ 1,
  v0211==3 & v0213==1 ~ 0,
  v0211==3 & v0213==3 ~ 1,
  TRUE ~ as.numeric(NA)
)

Notice that each case is defined as condicao ~ resultado se verdadeiro and separated by commas. Conditions are evaluated sequentially, as is ifelse . The last condition TRUE ~ NA , indicates that the NA value will be included if none of the previous ones is matched. To have the function case_when , load the package with library(dplyr) .

Note that : the call limit is not related to ifelse but to R. R limits the number of functions that can be called one within another (called < in> parse context ). Here's an example:

f <- function(x) return(1)

f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f(f())))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
Error: contextstack overflow at line 1

The R boundary is set to 50 calls. E is defined in this line of the R. source code. Or either to change this limit you need to change the source code of R. Here's a reference in stackoverflow

    
05.12.2016 / 13:14