Changing my answer, actually there is a previous problem, you would have to use the lapply
instead of apply
, because apparently the apply
will play everything to an array and convert to character
before returning to the data.frame
(had not tested the code before).
Generating fictitious 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
(doesn’t 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 the 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 above code, put the error message and a playable example so 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
Can you show a piece of the data variable? Is it a data frame, an array? Are there any columns other than those listed in the factor vector?
– rodrigorgs