3

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?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Dr. Fabian Habersack
  • 1,111
  • 12
  • 30
  • I'm afraid once you have a `factor` with different `labels`, you can't get back the original value. This https://stackoverflow.com/questions/39779688/how-to-preserve-original-values-in-a-variable-turned-into-a-factor looks a similar question but has no answer. – Ronak Shah Sep 13 '19 at 11:01
  • @RonakShah OK, but I am sure that it's possible to create a factor that takes values 1 or 2 and specify that 1 stands for "label_a", and 2 represents "label_b". So if you change the variable values, say from {1,0} to {1,2}, it should also be possible to assign new labels, right? – Dr. Fabian Habersack Sep 13 '19 at 11:23

1 Answers1

0

As mentioned in the comments once we have factor with labels we lose the initial value. We can try to store data in named vector or list instead

#Label can be considered as name of the vector
a <- c(yes = 1, no = 2)
#We can now change the value where a == 2 to 0 and labels are still intact
a[a == 2] <- 0
a
#yes  no 
#  1   0 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213