With anna.table (by the way, this is a data frame, a table is something else!), The easiest way is simply:
anna.table2 <- data.matrix(anna.table)
as data.matrix() converts factors into their basic numerical (integer) levels. This will work for a data frame that contains only numeric, integer, multipliers, or other variables that can be forced to be numeric, but any character strings (character) will make the matrix become a character matrix.
If you want anna.table2 be a data frame, not a matrix, you can subsequently:
anna.table2 <- data.frame(anna.table2)
Other parameters are forcing all variable factors to their whole levels. Here is an example of this:
#
What gives:
> str(dat) 'data.frame': 10 obs. of 2 variables: $ a: Factor w/ 3 levels "a","b","c": 1 2 2 3 1 3 3 2 2 1 $ b: num 0.206 0.177 0.687 0.384 0.77 ... > str(dat2) 'data.frame': 10 obs. of 2 variables: $ a: num 1 2 2 3 1 3 3 2 2 1 $ b: num 0.206 0.177 0.687 0.384 0.77 ...
However, note that the above will only work if you want to get a basic numeric representation. If your factor has substantially numerical levels, then we need to be a little smarter in how we convert the coefficient to numerical, preserving the βnumericalβ information encoded at the levels. Here is an example:
#
Note that we need to do as.character(x) before we do as.numeric() . An extra call encodes level information before we convert it to numeric. To understand why this matters, note that dat3$a
> dat3$a [1] 1 2 2 3 1 3 3 2 2 1 Levels: 3 2 1
If we just convert this to a numeric number, we get the wrong data, since R converts the codes of the basic level.
> as.numeric(dat3$a) [1] 3 2 2 1 3 1 1 2 2 3
If we first force the factor to a character vector, and then to a numerical one, we store the original information, and not the internal representation of R
> as.numeric(as.character(dat3$a)) [1] 1 2 2 3 1 3 3 2 2 1
If your data is similar to this second example, you cannot use the simple data.matrix() trick, since it is the same as applying as.numeric() directly to the coefficient and, as this second example shows, which does not preserve the original information.