ifelse
will return a vector the same length as the test (not what you want), useif(){}else{}
insteadYou have more than 40 unique values in
y
, so your function will not coerce it to factor.sapply will coerce the results to a matrix, which will force all variables to be the same "class"
What you want to do is use lapply
, and then replace the contents of the original.
dfr[] <- lapply(dfr, function(x) if(length(unique(x)) <=32) { as.factor(x)} else{x})
# It works!
str(dfr)
# 'data.frame': 40 obs. of 2 variables:
# $ y: Factor w/ 5 levels "0","1","2","3",..: 2 1 2 1 5 3 5 1 5 1 ...
# $ z: num 0.9036 0.2909 -0.9027 -0.4588 -0.0495 ...