Reputation: 11
I want to check if there are less than 4 uniques in my variable, and it's true, I want to create a factor from it.
I created a function:
checker <- function(x) {
if (is.numeric(x) == TRUE) {
if (length(unique(x)) < 5) {
x <- factor(x)
}
} else {
break
}
return(x)
}
But it still returns numeric vectors.
I suppose, for some reason
x <- factor(x)
doesn't work, when I tried:
checker <- function(x) {
x <- factor(x)
return(x)
}
The cycle returns numeric values
Upvotes: 0
Views: 177
Reputation: 389165
You can try this function
checker <- function(x) {
if (is.numeric(x) & length(unique(x)) < 5)
factor(x)
else x
}
and then apply it using lapply
df[] <- lapply(df, checker)
str(df)
#'data.frame': 6 obs. of 2 variables:
# $ a: Factor w/ 4 levels "1","2","3","4": 1 2 3 3 4 3
# $ b: int 1 2 3 4 5 6
Or as @akrun suggests an option with dplyr
would be
library(dplyr)
df %>% mutate_if(~ is.numeric(.) && n_distinct(.) < 5, factor)
data
df <- data.frame(a = c(1, 2, 3, 3, 4, 3), b = 1:6)
Upvotes: 1
Reputation: 102309
Try the function below:
checker <- function(x) ifelse(length(unique(x))< 5, return(factor(x)), return(x))
Upvotes: 0