3

I thought I perfectly understood the factor class in R, but finally, I may not. I can't find a way to transform a vector of 0/1 into a factor without transforming the original value in 1/2. Here is a minimal working example:

foo<-c(1,0,0,1,1,1,0,NA,0,1)
bar<-factor(foo)
str(bar)

results in:

Factor w/ 2 levels "0","1": 2 1 1 2 2 2 1 NA 1 2

and

bar<-factor(foo, labels = c("(0) No", "(1) Yes"))
str(bar)

results in:

Factor w/ 2 levels "(0) No","(1) Yes": 2 1 1 2 2 2 1 NA 1 2

and

bar<-factor(foo, levels= c(0,1), labels = c("(0) No", "(1) Yes"))
str(bar)

results in:

Factor w/ 2 levels "(0) No","(1) Yes": 2 1 1 2 2 2 1 NA 1 2

Is it because R can have a level equal to 0?

I really want to keep the original values as 0/1 to facilitate data sharing, but could someone provide a solution?

  • 5
    The original values are the ones you had before. The 1/2 thing you see in `str` is the position of the value. That's why it will always include 1. It will help you understand the connection between value and position/number if in each case you run `str(bar); bar; as.character(bar); as.numeric(bar)` – AntoniosK Feb 01 '18 at 16:57
  • 1
    What do you expect `levels = c(0,1)` to do? Change it so that `as.numeric(bar)` returns a vector of values in `0,1` rather than `1,2`? – John Coleman Feb 01 '18 at 17:06
  • Thank you so much! – Guillaume Béraud Feb 01 '18 at 17:07
  • Why do you want a factor? What is wrong with integer 0 and 1? – dcarlson Feb 01 '18 at 22:20
  • 1
    There is nothing wrong with 0 and 1, indeed it is how I prefer it. However, I have to perform statistical analysis (which is not a problem) but also to provide a clean data file for other researchers who would like to work on it. Hence, I have to follow adapt my workflow to the local habits – Guillaume Béraud Feb 02 '18 at 20:30

0 Answers0