问题
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.
回答1:
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"
来源:https://stackoverflow.com/questions/22350188/creating-a-logical-variable-out-of-a-factor-variable-in-r