Reputation: 6213
I am getting unexpected results from the ifelse
function :
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"
Any idea what's going on?
Upvotes: 3
Views: 199
Reputation: 206197
I think you just want to use an if
statement. Not ifelse()
. The latter is meant to work with vectors and return a vector with length equal to that of the input. if you want to return a different number of elements for different conditions, just use if
.
vector <- factor(c('x', 'x', 'y', 'z'), levels = c('x', 'y', 'z'))
xx <- if(class(vector) == "factor") levels(vector) else unique(vector)
xx
Upvotes: 7