Reputation: 2430
My task:
In the below case, CA + CC should change to factorial
.
CA = c(1,0,1,0,1)
CB = c(1,12,21,0,7)
CC = c(1,0,1,0,1)
mydf = data.frame(CA, CB, CC)
str(mydf)
'data.frame': 5 obs. of 3 variables:
$ CA: num 1 0 1 0 1
$ CB: num 1 12 21 0 7
$ CC: num 1 0 1 0 1
Why? Because these rows are currently depicted as integer
and number
instead of factors
. And I assume that some ML-algorithms mix things up.
Upvotes: 1
Views: 78
Reputation: 388982
Just another way to do it in base R
cols <- colSums(mydf == 0 | mydf == 1) == nrow(mydf)
mydf[cols] <- lapply(mydf[cols], as.factor)
str(mydf)
#'data.frame': 5 obs. of 3 variables:
# $ CA: Factor w/ 2 levels "0","1": 2 1 2 1 2
# $ CB: num 1 12 21 0 7
# $ CC: Factor w/ 2 levels "0","1": 2 1 2 1 2
Upvotes: 2
Reputation: 2299
Another approach with dplyr
's mutate_if
library(dplyr)
is_one_zero <- function(x) {
res <- all(unique(x) %in% c(1, 0))
return(res)
}
out <- mydf %>%
mutate_if(is_one_zero, as.factor)
str(out)
#'data.frame': 5 obs. of 3 variables:
# $ CA: Factor w/ 2 levels "0","1": 2 1 2 1 2
# $ CB: num 1 12 21 0 7
# $ CC: Factor w/ 2 levels "0","1": 2 1 2 1 2
Upvotes: 2
Reputation: 37879
One way with baseR:
#if all the values in a column are either 0 or 1 convert to factor
mydf[] <- lapply(mydf, function(x) {
if(all(x %in% 0:1)) {
as.factor(x)
} else {
x
}
})
Out:
str(mydf)
#'data.frame': 5 obs. of 3 variables:
# $ CA: Factor w/ 2 levels "0","1": 2 1 2 1 2
# $ CB: num 1 12 21 0 7
# $ CC: Factor w/ 2 levels "0","1": 2 1 2 1 2**
Upvotes: 2