Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a logical variable out of a factor variable in R

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.

like image 1000
Pulse Avatar asked Mar 21 '23 06:03

Pulse


1 Answers

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"
like image 181
Sven Hohenstein Avatar answered Mar 23 '23 13:03

Sven Hohenstein