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'`
– José Jaime da Silva
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.– Daniel Falbel
It worked Thank you
– José Jaime da Silva