Question

I need to create a logical variable (True-False) out of a categorical (factor) variable

I decided to use the:

 dat$var[dat$var %in% c("option1")] <- TRUE
 dat$var[dat$var %in% c("option2")] <- FALSE

But I get the following error message in both lines and my entire variable is NA:

Warning message:
In `[<-.factor`(`*tmp*`, dat$var %in% c("option1"),  :
   invalid factor level, NA generated

Any ideas on what I might be doing wrong? The factor level is right, I copy pasted to make sure there will not be any typos. I thought of changing the variable to vector as.logical() but that didn't work either.

Was it helpful?

Solution

This error is due to dat$var being a factor. You can only assign values of pre-specified levels to a factor variable. But you can create the new variable with the following command (assuming option1 and option2 are the only values):

dat$var <- dat$var == "option1"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top