2

Very basic but how can expand a factor vector, without to coerce into a numeric vector?

# a simple numeric vector
x <- c(1, 2, 3) 
# wants to convert into a factor vector
x <- factor(x, levels = c(1, 2, 3, 4), labels = c("can", "see", "the", "moon?"))

# Apparently he does
is.factor(x)
[1] TRUE

print(x)
[1] can see the
Levels: can see the moon?

# but when he want to expand his horizon
x <- c(x, 4)

# his dignity was revoked
print(x)
[1] 1 2 3 4

It appears to the numeric class has more priority than the factor class, and when we concatenate x with a number, R can not reason: incorporate a level into this vector-factor. But the argument levels allow to specify values that are not in the current vector, this can have sense like a mechanism to expand the elements of a factor-vector, in the sense of possible elements that could contained in it. More than a recyclable purpose of the script to apply after an expansion of the vector.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Cristóbal Alcázar
  • 1,153
  • 14
  • 26

0 Answers0