I would like to do three things step by step and I am unfortunately stuck. Maybe someone could walk me through the process in R or point out my mistakes.
# Create a dataset containing a factor with pre-defined levels and labels
testdat<-data.frame(a=factor(c(1,2), labels=c("yes","no")))
I was expecting to get a factor, named "a", that takes on the values 1 and 2 and is assigned labels "yes" (for 1), and "no" (for 2). Unfortunately, the factor now only contains what I specified as labels, but c(1,2) is not accessible anymore.
# Next, I would like to assign new levels to the factor, namely {1,0} instead of {1,2}
testdat$a[testdat==2] <- 0
Obviously this doesn't work, because the problems in the first step and because there is no value ==2
. But ideally, after this second step, I would have a variable "a" that now takes values 1 and 0, but that has still the original labels "yes" (for 1) and "no" (for 2) assigned.
So in a third step, I would like to adjust the value labels so that "no" corresponds to value 0, and no longer two (no longer present) value 2. How would I do that?
And should this be a community wiki?