Creating a logical variable out of a factor variable in R

对着背影说爱祢 提交于 2020-07-08 11:49:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!