how to increase the limit of ifelse in R?

Asked

Viewed 302 times

5

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

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

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

1 answer

4


One possible way is to use the case_when of dplyr. I did some tests and did not find the limitation of many cases as the ifelse has. In your case, would be so:

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

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

Note that: the call limit is not related to ifelse and yes to R. O R limits the number of functions that can be called within each other (called parse context). Take this 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 limit is set to 50 calls. And is set in this line of the R source code. That is, to change this limit you need to change the R source code. It follows a reference in stackoverflow

  • Thank you. now this error has appeared Error: RHS of case 123 (NA) has type 'Logical' not 'double'`

  • I edited the answer. Add: as.Numeric(NA) in the last condition. A case_when does not let different types appear in the same vector.

  • 1

    It worked Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.