来自ifelse的意外结果

时间:2017-12-14 15:17:37

标签: r

我从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"

知道发生了什么事吗?

1 个答案:

答案 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