[英]How to dichotomize categorical variables into a new variable with 1s and 0s but maintain NAs?
I am trying to create a new variable within my data frame to encapsulate questions with two categorical answers.我正在尝试在我的数据框中创建一个新变量,以用两个分类答案封装问题。 I would like to be able to convert these to 1s and 0s.我希望能够将这些转换为 1 和 0。
I've been using the ifelse()
function but I feel like it inherently wants to convert NA
values into 0s in my case.我一直在使用ifelse()
function 但我觉得它天生就想将NA
值转换为 0 在我的情况下。 Adding the na.rm=TRUE
argument onto the end gives me an error.在末尾添加na.rm=TRUE
参数会给我一个错误。
data$Knowledge=ifelse(data$Variable=="Yes",1,0, na.rm=TRUE)
Error in ifelse(data$Sabe.qué.trata.la.Ley.No.26378..Convención.sobre.los.Derechos.de.las.personas.con.discapacidad..sobre.las.personas.Sordas.o.hipoacúsicas. ==: unused argument (na.rm = TRUE) ifelse 错误(数据$Sabe.qué.trata.la.Ley.No.26378..Convención.sobre.los.Derechos.de.las.personas.con.discapacidad..sobre.las.personas.Sordas.o. hipoacúsicas. ==: 未使用的参数 (na.rm = TRUE)
ifelse()
doesn't have an na.rm
argument (in any case, you don't want to remove NA
values, you want to pass them on in the result). ifelse()
没有na.rm
参数(无论如何,您不想删除NA
值,您想在结果中传递它们)。 A solution with explicit logic: nested ifelse
具有显式逻辑的解决方案:嵌套ifelse
x <- c("Yes","No",NA)
ifelse(is.na(x),NA,ifelse(x=="Yes",1,0))
A more efficient solution based on coercion of logical values to integers ( TRUE
-> 1, FALSE
-> 0, NA
-> NA
)基于将逻辑值强制转换为整数( TRUE
-> 1, FALSE
-> 0, NA
-> NA
)的更有效的解决方案
as.integer(x=="Yes")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.