Alex Rivera | Logout

How do I change a value coded as "Yes" to a value of 1 in R?

Asked 2012-08-19T23:02:18.727
9

The variables in my database are coded as "Yes" and "No" but I would like to have as "1" and "2".

I tried to create a new variable using ifelse but when I list'ed it, it didn't work, as follows:

CA <- ifelse((CANCER == "Yes"),1
ifelse(( CANCER == "No"),2 )))

list(CA)

[[1]]
NULL
r
Edit
Report

1 Answer

2

We need to know if your variable is a factor. Suppose

foo <- c("yes","no","no","yes")

If is.factor(foo) returns TRUE, e.g., if you did foo <- factor(foo), then use

levels(foo) <- c("2", "1")

else use

foo[foo == "yes"] <- 1
foo[foo == "no"] <- 2

Also, list() doesn't do what (I think) you think it does. If you want to view the value of foo, just type in foo. After executing the code above...

foo
[1] 1 2 2 1
answered 2012-08-19T23:35:49.993

Your Answer