在R中的因子变量之外创建逻辑变量 [英] Creating a logical variable out of a factor variable in R

查看:54
本文介绍了在R中的因子变量之外创建逻辑变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从分类(因子)变量中创建一个逻辑变量(True-False)

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

我决定使用:

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

但是我两行都收到以下错误消息,并且我的整个变量都是NA:

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

关于我可能做错了什么的任何想法?因素水平是正确的,我复制粘贴以确保不会出现任何错别字.我曾想过将变量更改为向量 as.logical(),但这也不起作用.

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.

推荐答案

此错误是由于 dat $ var 是一个因素造成的.您只能将预先指定级别的值分配给因子变量.但是您可以使用以下命令创建新变量(假设只有 option1 option2 是唯一的值):

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"

这篇关于在R中的因子变量之外创建逻辑变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆