Sunday 21 June 2015

R : factors

Factors are used to represent categorical data. Factors in R are stored as a vector of integer values with a corresponding set of character values to use when the factor is displayed. By using factor() function, you can create a factor.  

There are two types of factors
                  a. ordered
                  b. unordered

Factors represent a very efficient way to store character values, because each unique character value is stored only once, and the data itself is stored as a vector of integers.
> months <- c("January", "February", "March", "April", "May", "June", "July","August", "January", "March", "september", "April", "June", "May", "June")
> monthsFact <- factor(months)
>
> monthsFact
 [1] January   February  March     April     May       June      July      August    January   March     september April     June      May       June     
Levels: April August February January July June March May september
>
> table(monthsFact)
monthsFact
    April    August  February   January      July      June     March       May september 
        2         1         1         2         1         3         2         2         1

As you observe above output, months are not displayed in order. If you want to display months in order, create ordered factor.
> monthsFact <- factor(months, levels=c("January","February","March", "April","May","June","July","August","September", "October","November","December"),ordered=TRUE)
> 
> monthsFact
 [1] January  February March    April    May      June     July     August   January  March    <NA>     April    June     May      June    
Levels: January < February < March < April < May < June < July < August < September < October < November < December
> 
> table(monthsFact)
monthsFact
  January  February     March     April       May      June      July    August September   October  November  December 
        2         1         2         2         2         3         1         1         0         0         0         0 
>


References



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment