我从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"
Run Code Online (Sandbox Code Playgroud)
知道发生了什么事吗?
我想你只想用一个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
Run Code Online (Sandbox Code Playgroud)