Changing my answer, there is actually a previous problem, you would have to use lapply
instead of apply
, because apparently apply
will throw everything to an array and convert to character
before returning for data.frame
(had not tested the code before).
Generating a dummy data to illustrate:
dados <- data.frame(x = 1:10)
dados[, fatores] <- rep(c("a", "b", "c", "d"),10)
str(dados)
data.frame': 10 obs. of 5 variables:
$ x : int 1 2 3 4 5 6 7 8 9 10
$ Year : chr "a" "b" "c" "d" ...
$ Month : chr "c" "d" "a" "b" ...
$ DayofWeek : chr "a" "b" "c" "d" ...
$ DayofMonth: chr "c" "d" "a" "b" ...
With apply
(does not work):
dados[,fatores]= apply(dados[,fatores], 2, as.factor)
str(dados)
'data.frame': 10 obs. of 5 variables:
$ x : int 1 2 3 4 5 6 7 8 9 10
$ Year : chr "a" "b" "c" "d" ...
$ Month : chr "c" "d" "a" "b" ...
$ DayofWeek : chr "a" "b" "c" "d" ...
$ DayofMonth: chr "c" "d" "a" "b" ...
With lapply
(works):
dados[,fatores]= lapply(dados[,fatores], as.factor)
str(dados)
'data.frame': 10 obs. of 5 variables:
$ x : int 1 2 3 4 5 6 7 8 9 10
$ Year : Factor w/ 4 levels "a","b","c","d": 1 2 3 4 1 2 3 4 1 2
$ Month : Factor w/ 4 levels "a","b","c","d": 3 4 1 2 3 4 1 2 3 4
$ DayofWeek : Factor w/ 4 levels "a","b","c","d": 1 2 3 4 1 2 3 4 1 2
$ DayofMonth: Factor w/ 4 levels "a","b","c","d": 3 4 1 2 3 4 1 2 3 4
If an error appears in the code above, put the error message and a reproducible example so that we can understand what the problem is and the result of head(dados)
and str(dados)
in your question to see what the object is like >