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.
I've been using the ifelse()
function but I feel like it inherently wants to convert NA
values into 0s in my case. Adding the na.rm=TRUE
argument onto the end gives me an error.
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()
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). A solution with explicit logic: nested 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
)
as.integer(x=="Yes")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.