我从ifelse
函数获得意外结果:
vector <- factor(c('x', 'x', 'y', 'z'), levels = c('x', 'y', 'z'))
ifelse(class(vector) == "factor", yes = levels(vector), no =
unique(vector)) # Returns character "x" and not the expected c("x", "y",
"z")
# Manual debug
class(vector) == "factor" # TRUE
levels(vector) # [1] "x" "y" "z"
知道发生了什么事吗?
答案 0 :(得分:6)
我想你只想使用if
声明。不是ifelse()
。后者用于处理向量并返回长度等于输入长度的向量。如果您想为不同的条件返回不同数量的元素,请使用if
。
vector <- factor(c('x', 'x', 'y', 'z'), levels = c('x', 'y', 'z'))
xx <- if(class(vector) == "factor") levels(vector) else unique(vector)
xx