0

The factor() function is incrementing my zeros to ones and ones to twos. Here's a simple example:

# Create some integers
ints <- as.integer(c(1,0,1))
ints
[1] 1 0 1

# Convert these to factors
f_ints <- factor(ints)
f_ints 
[1] 1 0 1
Levels: 0 1

# Great! Let's just check one more thing...
str(f_ints)
Factor w/ 2 levels "0","1": 2 1 2

# Woah, whats up with those twos? 

# Screw this, let's go back to integers
ints_again <- as.integer(f_ints)
ints_again
[1] 2 1 2

What accounts for this behavior? I thought this question and this question might explain this, but they're not the same.

Community
  • 1
  • 1
ojdajuiceman
  • 361
  • 2
  • 9
  • 3
    Those questions are basically the same. Factors assign non-zero integers to each of the unique values. They are meant for categorical variables. As the answers in the other questions indicate, do not use `as.integer()` on factors. Use `as.interger(as.character())`. I'm not sure what the specific behavior here is that differs from the other questions. – MrFlick Mar 09 '16 at 05:57
  • "Factors assign non-zero integers to each of the unique values." That's helpful, thanks @MrFlick. – ojdajuiceman Mar 09 '16 at 19:39

1 Answers1

0

convert to character before converting to integer like:

ints_again <- as.integer(as.character(f_ints))
vdep
  • 3,541
  • 4
  • 28
  • 54