Factors
Since we are talking about strings, it is important to mention factors in R. These are objects used to create categorical variables, whether those categories are ordered or not. Categories can be text or numbers, for instance. We can create a factor variable using factor()
:
# Textual variable var <- c('A', 'B', 'B', 'C', 'A', 'C') # To create a factor factor_var <- factor(var)
And, subsequently, you can see what the environment shows:
Figure 4.14 – Text variable and factor variable
As seen in Figure 4.5, the levels have been created and the order assigned is alphabetical. If we want to change that, we can use levels()
:
# Ordered levels levels(factor_var) <- c('C','B','A') factor_var [1] C B B A C A Levels: C B A
If we print the variable again after changing the order, see how 1 2 2 3 1 3
now becomes C B B A C A
, confirming that the levels...