我从 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"
知道发生了什么吗?
最佳答案
我认为您只想使用 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
关于r - ifelse 的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47816693/