# Factor Variables {#factors}

Learning Objectives

In this chapter you'll learn:

- How R encodes categorical variables

Factors variables are explanatory, categorical variables. Knowing how to set-up and use factors in R is an important aspect of data analysis.^[Explanatory variables are used when comparing and summarizing measured values of different groups, such as control versus treatment. The measured value is a response variable to the explanatory variable.]

## The Structure of Factors

A factor is a class that can be assigned to any of the atomic vector types.^[See \@ref(chap:Different-Kinds-of) for a review of the different atomic vector types.] When this occurs, the underlying vector is converted to an integer and its values are saved as a character vector which is then used to describe the levels.


Recall in `foo_df`:

```{r}

# Our original character vector
foo3
typeof(foo3)
class(foo3)

# We used foo3 to make foo_df$tissue
foo_df$tissue
typeof(foo_df$tissue)

# Which was converted to a factor:
class(foo_df$tissue)
```

This can be a major space saving mechanism. Imagine saving many labels thousands of times over in a very large data frame, it takes up a lot of memory. R just needs to save a single integer for each label and stores the label as a character only once.

In R, factors are all simple integer vectors assigned a class of factor. This means that they have an associated character vector to describe the levels.

## Factors and defining Linear Models

Let's take a look at how Factors can affect how our statistics are performed. Recall that for the `PlantGrowth` data set we used:

```{r}
class(PlantGrowth$group)
levels(PlantGrowth$group)

# tapply(PlantGrowth$weight, PlantGrowth$group, mean)

summary(lm(weight ~ group, data = PlantGrowth))
```


```{r}
# Reorder the levels
PlantGrowth$group <- factor(PlantGrowth$group,
                            levels = c("trt2", "trt1", "ctrl"))
levels(PlantGrowth$group)
```


```{r}
summary(lm(weight ~ group, data = PlantGrowth))
```

The ANOVAs are different because the order of the factors was different! The first level is used as the reference.

Let's consider what happens when `group` is a character and not a factor:

```{r}
myDF <- PlantGrowth
myDF$group <- as.character(myDF$group)
str(myDF)
```


```{r}
# tapply(myDF$weight, myDF$group, mean)
summary(lm(weight ~ group, data = myDF))
```


We get the same results! Under the hood, R has quietly converted our character vector to a factor. However, here we don't have any say as to the order the levels will be used. It is always advantageous to manually establish our factors.

## Factors and Importing Data

Review the section on the `stringsAsFactors` argument in the importing data section. When data is imported into R, each variable is automatically assigned a type If a column contains characters, R v4.0 and above will give assign is as such when using the `read.*()` functions. Earlier versions will think it's a categorical variable, and classify it as a factor, unless you set `stringsAsFactors = FALSE`.

## Converting from Factors to other Classes

Converting between factor and other classes can be troublesome. If the labels are numerical, you cannot simply call `as.numeric()`. They must first be converted to characters and then to numbers:

```{r}

foo5 <- 21:30
typeof(foo5)
class(foo5) # An integer vector
foo5

foo5 <- as.factor(foo5)
typeof(foo5)
class(foo5) # A integer vector of factor class
foo5

# What is actually stored (like an ID).
labels(foo5)
# The names of the levels assigned to each label, in order
levels(foo5)

foo5 <- as.integer(foo5) # or also use as.numeric()
typeof(foo5)
class(foo5) # A numeric vector, but...
# This takes the labels, not the levels assigned to those labels
foo5 # The values are gone!! Bad Move!!

# Do this instead:
foo5 <- as.factor(21:30) # re-establish factor
foo5 <- as.numeric(as.character(foo5))
typeof(foo5)
class(foo5) # A numeric vector with the proper values
foo5
```

## Ordered Factors

Recall that there are two types of categorical variables, nominal and ordinal. So far we have only been dealing with ordinal variables, but we can also add order to a factor, as in:

```{r}

foo6 <- c("small", "large", "small", "medium", "small", "medium")
factor(foo6) # improper order
# labels don't exist!
factor(foo6, levels = c("low", "middle", "high"))
# proper order
factor(foo6, levels = c("small", "medium", "large"))
# defined proper order. factor(x, ordered=TRUE) is also possible.
ordered(foo6, levels = c("small", "medium", "large"))
```

## Adding & Removing Factors Levels

To add new information to a factor, we fist have to add the new level. This is because we have already defined all the possible categories for the categorical variable in R.

```{r}

# create a 6-element long factor
foo7 <- factor(foo6,
               levels = c("small", "medium", "large"))
levels(foo7)
foo7[7] <- "extra large"
foo7
levels(foo7)
foo7 <- factor(foo7, levels = c(levels(foo7), "X_large"))
foo7[7] <- "X_large"
foo7
```

If we want to drop a level after removing all occurrences of a group, we just have to reestablish our factor.

```{r}

foo7 <- foo7[foo7 != "small"]
# Old levels remain in the character vector.
# We need to reinitialize the factor to get rid of them.
foo7
foo7 <- factor(foo7)
foo7
```

## Relabeling Factors Levels

Factor levels are just character vectors, like what we saw for the column names in a data frame. This means that we only have to change the label in the character vector to change all occurrences of that label in the factor.

```{r eval = F}
# The levels for the tissue factor
foo_df$tissue <- as.factor(foo_df$tissue)
foo_df$tissue
levels(foo_df$tissue)
```

The levels are stored as a character vector, so we can just change the a level directly:

```{r eval = F}
levels(foo_df$tissue)[5] <- "Tongue"
foo_df$tissue
```

Or we can specify it using a regular expression: in the `grep()` function. `"^B"` means _look for anything that begins with a capital B_:

```{r eval = F}
levels(foo_df$tissue)[grep("^B", levels(foo_df$tissue))] <- "Forebrain"
foo_df$tissue
```

