Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 90
4.3.7.1 Creating Factors
ОглавлениеFactors are created using factor()
the function.
factor()
# Create a vector containing all your observations: feedback <- c(‘Good’,‘Good’,‘Bad’,‘Average’,‘Bad’,‘Good’) # Create a factor object: factor_feedback <- factor(feedback) # Print the factor object: print(factor_feedback) ## [1] Good Good Bad Average Bad Good ## Levels: Average Bad Good
From the aforementioned example it is clear that the factor-object “is aware” of all the labels for all observations as well as the different levels (or different labels) that exist. The next code fragment makes clear that some functions – such as plot()
– will recognize the factor-object and produce results that make sense for this type of object. The following line of code is enough to produce the output that is shown in Figure 4.1.
# Plot the histogram -- note the default order is alphabetic plot(factor_feedback)
Figure 4.1: The plot-function will result in a bar-chart for a factor-object.
There are a few specific functions for the factor-object. For example, the function nlevels()
returns the number of levels in the factor object.
nlevels()
# The nlevels function returns the number of levels: print(nlevels(factor_feedback)) ## [1] 3