Alternatively - and potentially more flexible if you have more than 2 options - you can use the merge()
function.
For example if you have this data frame:
dtf <- data.frame(CANCER = c("No", "Yes", "Yes", "No"),
x = c(4, 5, 6, 7),
# Keep character variables as characters, do not create factors
stringsAsFactors = FALSE)
You can store the new way to code the value in another data frame :
moreinfo <- data.frame(CANCER = c("Yes", "No"),
CA = c(1, 2),
stringsAsFactors = FALSE)
Then merge it with the original data frame:
merge(dtf, moreinfo, by = "CANCER")
CANCER x CA
1 No 4 2
2 No 7 2
3 Yes 5 1
4 Yes 6 1
Note: sorry about the stringsAsFactors
parameter, it's necessary to prevent R from automatically creating factors with your character variables, I recommend using it also when you load data with read.csv()
.