Convert qualitative numerical variables into factors in R

1

I have the following code, READY, that my supervisor passed to me

fatores=c("Year","Month","DayofWeek","DayofMonth")

dadosFatores=apply(dados[,fatores],2,XXXX)

dados[,XXXX]=dadosFatores

In the exercise says that I should only change the XXXX to something that makes sense and return what the function asks, ie convert the variables into question into factors.

I tried to replace with as.factor , without much success.

Could someone help?

    
asked by anonymous 26.11.2014 / 03:57

1 answer

3

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 >     

26.11.2014 / 13:35