Factors form the basis for many of R’s powerful operations, including many of those performed on tabular data.
The motivation for factors comes from the notion of nominal, or categorical, variables in statistics. These values are nonnumerical in nature, corresponding to categories such as Democrat, Republican, and Unaffiliated, although they may be coded using numbers.
## [1] 5 12 13 12
## Levels: 5 12 13
## Factor w/ 3 levels "5","12","13": 1 2 3 2
## [1] 1 2 3 2
## attr(,"levels")
## [1] "5" "12" "13"
## [1] "5" "12" "13"
## [1] 4
## [1] 5 88 13 12
## Levels: 5 12 13 88
As motivation, suppose we have a vector x of ages of voters and a factor f showing some nonumeric trait of those voters, such as party affiliation (Democrat, Republican, Unaffiliated). We might wish to find the mean ages in x within each of the party groups.
In typical usage, the call tapply(x,f,g) has x as a vector, f as a factor or list of factors, and g as a function. The function g() in our little example above would be R’s built-in mean() function. If we wanted to group by both party and another factor, say gender, we would need f to consist of the two factors, party and gender.
Each factor in f must have the same length as x. This makes sense in light of the voter example above; we should have as many party affiliations as ages. If a component of f is a vector, it will be coerced into a factor by applying as.factor() to it.
The operation performed by tapply() is to (temporarily) split x into groups, each group corresponding to a level of the factor (or a combination of levels of the factors in the case of multiple factors), and then apply g() to the resulting subvectors of x. Here’s a little example:
## D R U
## 41 31 21
The function tapply() treated the vector (“R”,“D”,“D”,“R”,“U”,“D”) as a factor with levels “D”, “R”, and “U”. It noted that “D” occurred in indices 2, 3 and 6; “R” occurred in indices 1 and 4; and “U” occurred in index 5. For convenience, let’s refer to the three index vectors (2,3,6), (1,4), and (5) as x, y, and z, respectively. Then tapply() computed mean(u[x]), mean(u[y]), and mean(u[z]) and returned those means in a three-element vector. And that vector’s element names are “D”, “R”, and “U”, reflecting the factor levels that were used by tapply().
What if we have two or more factors? Then each factor yields a set of groups, as in the preceding example.
suppose that we have an economic data set that includes variables for gender, age, and income. Here, the call tapply(x,f,g) might have x as income and f as a pair of factors: one for gender and the other coding whether the person is older or younger than 25. We may be interested in finding mean income, broken down by gender and age. If we set g() to be mean(), tapply() will return the mean incomes in each of four subgroups:
Here’s a toy example of that setting:
d <- data.frame(list(
gender=c("M","M","F","M","F","F"),
age=c(47,59,21,32,33,24),
income=c(55000,88000,32450,76500,123000,45650)))
d## 0 1
## F 39050 123000.00
## M NA 73166.67
## $F.0
## [1] 32450 45650
##
## $M.0
## numeric(0)
##
## $F.1
## [1] 123000
##
## $M.1
## [1] 55000 88000 76500
Suppose in the abalone example we wish to do regression analyses of diameter against length separately for each gender code: males, females, and infants. At first, this seems like something tailor-made for tapply(), but the first argument of that function must be a vector, not a matrix or a data frame. The function to be applied can be multivariate—for example, range()—but the input must be a vector. Yet the input for regression is a matrix (or data frame) with at least two columns: one for the predicted variable and one or more for predictor variables. In our abalone data application, the matrix would consist of a column for the diameter data and a column for length.
The by() function can be used here. It works like tapply() (which it calls internally, in fact), but it is applied to objects rather than vectors. Here’s how to use it for the desired regression analyses:
abaloneDataURL<- 'https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data'
aba <- read.csv(abaloneDataURL,header=FALSE,as.is=T)
names(aba)[1:9] <- c("Gender","Length","Diameter","Height","WholeWt","ShuckedWt","ViscWt","ShellWt","Rings")
aba## aba$Gender: F
##
## Call:
## lm(formula = m[, 2] ~ m[, 3])
##
## Coefficients:
## (Intercept) m[, 3]
## 0.04288 1.17918
##
## ------------------------------------------------------------
## aba$Gender: I
##
## Call:
## lm(formula = m[, 2] ~ m[, 3])
##
## Coefficients:
## (Intercept) m[, 3]
## 0.02997 1.21833
##
## ------------------------------------------------------------
## aba$Gender: M
##
## Call:
## lm(formula = m[, 2] ~ m[, 3])
##
## Coefficients:
## (Intercept) m[, 3]
## 0.03653 1.19480
Calls to by() look very similar to calls to tapply(), with the first argument specifying our data, the second the grouping factor, and the third the function to be applied to each group.
Just as tapply() forms groups of indices of a vector according to levels of a factor, this by() call finds groups of row numbers of the data frame aba. That creates three subdata frames: one for each gender level of M, F, and I.
The anonymous function we defined regresses the second column of its matrix argument m against the third column. This function will be called three times—once for each of the three subdata frames created earlier— thus producing the three regression analyses.
u <- c(22,8,33,6,8,29,-2)
fl <- list(c(5,12,13,12,13,5,13),c("a","bc","a","a","bc","a","a"))
tapply(u,fl,length)## a bc
## 5 2 NA
## 12 1 1
## 13 2 1
## fl.2
## fl.1 a bc
## 5 2 0
## 12 1 1
## 13 2 1
The first argument in a call to table() is either a factor or a list of factors. The two factors here were (5,12,13,12,13,5,13) and (“a”,“bc”,“a”,“a”,“bc”, “a”,“a”). In this case, an object that is interpretable as a factor is counted as one.
Typically a data frame serves as the table() data argument. Suppose for instance the file ct.dat consists of election-polling data, in which candidate X is running for reelection. The ct.dat file looks like this:
## Voted.For.X.Last.Time
## Vote.for.X No Yes
## No 2 0
## Not Sure 0 1
## Yes 1 1
The 2 in the upper-left corner of the table shows that we had, for example, two people who said “no” to the first and second questions. The 1 in the middle-right indicates that one person answered “not sure” to the first question and “yes” to the second question.
We can also get one-dimensional counts, which are counts on a single factor, as follows:
##
## 5 8 12 13
## 2 1 2 1
v<-data.frame(
gender=c("M","M","F","M","F","F"),
race=c("W","W","A","O","B","B"),
pol=c("L","L","C","L","L","C"))
vt<-table(v)
vt## , , pol = C
##
## race
## gender A B O W
## F 1 1 0 0
## M 0 0 0 0
##
## , , pol = L
##
## race
## gender A B O W
## F 0 1 0 0
## M 0 0 1 2
Just as most (nonmathematical) matrix/array operations can be used on data frames, they can be applied to tables, too. (This is not surprising, given that the cell counts portion of a table object is an array.)
For example, we can access the table cell counts using matrix notation. Let’s apply this to our voting example from the previous section.
## [1] "table"
## [1] 2
## No Yes
## 2 0
In the second command, even though the first command had shown that cttab had class “cttab”, we treated it as a matrix and printed out its “[1,1] element.” Continuing this idea, the third command printed the first column of this “matrix.”
We can multiply the matrix by a scalar. For instance, here’s how to change cell counts to proportions:
## Voted.For.X.Last.Time
## Vote.for.X No Yes
## No 0.4 0.0
## Not Sure 0.0 0.2
## Yes 0.2 0.2
## No Not Sure Yes
## 2 1 2
## Voted.For.X.Last.Time
## Vote.for.X No Yes Sum
## No 2 0 2
## Not Sure 0 1 1
## Yes 1 1 2
## Sum 3 2 5
## $Vote.for.X
## [1] "No" "Not Sure" "Yes"
##
## $Voted.For.X.Last.Time
## [1] "No" "Yes"