非常基本,但如何扩展因子向量,而不是强制转换为数字向量?
# 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
似乎数字类的优先级高于因子类,当我们将x
与数字连接时, R无法推理:将一个级别合并到此向量因子 。但是参数levels
允许指定不在当前向量中的值,这可以像扩展因子向量的元素一样,在可能包含在其中的元素的意义上。在向量扩展后应用脚本的不仅仅是可循环使用的目的。