data.matrix vs data.frame and data.matrix vs as.matrix

Viewed 237

How do data.matrix and data.frame differ?

I understand that matrix and data.frame are different but I want to specifically know what are the differences between data.frame and data.matrix.

Are matrix and data.frame the same?

  • Is data.matrix the same as matrix in R?
  • Are conversion results of data.matrix and as.matrix the same? or how do they vary?
1 Answers

According to the R documentation (type ?data.matrix), data.matrix is a conversion function to transform a data.frame into a matrix which automatically transforms categorial data into numbers.

Even if the data.frame contains purely numeric data, the conversion can occasionally necessary to apply operations or functions that are only defined for matrices, e.g. multiplication:

> x <- mtcars[1:3, 1:2]
> x %*% c(1,2)
Error in x %*% c(1, 2) : requires numeric/complex matrix/vector arguments
> data.matrix(x) %*% c(1,2)
              [,1]
Mazda RX4     33.0
Mazda RX4 Wag 33.0
Datsun 710    30.8

Compared to as.matrix, the defualt type conversion rules are different:

> x <- data.frame(a=as.factor(c("a","b")), b=c(1,2))
> as.matrix(x)
     a   b  
[1,] "a" "1"
[2,] "b" "2"
> data.matrix(x)
     a b
[1,] 1 1
[2,] 2 2

Note that there is yet another function: model.matrix, which is used to compute from a data.frame and a formula the predictor array used in a linear model. Example:

> m <- lm(mpg ~ poly(wt, 2), data=mtcars)
> head(model.matrix(m), n=3)
              (Intercept) poly(wt, 2)1 poly(wt, 2)2
Mazda RX4               1  -0.10963100  -0.04278415
Mazda RX4 Wag           1  -0.06282329  -0.09005145
Datsun 710              1  -0.16469889   0.03540332

Or directly, without the detour across lm:

> m <- model.matrix(~poly(wt, 2), data=mtcars)
> head(m, n=3)
              (Intercept) poly(wt, 2)1 poly(wt, 2)2
Mazda RX4               1  -0.10963100  -0.04278415
Mazda RX4 Wag           1  -0.06282329  -0.09005145
Datsun 710              1  -0.16469889   0.03540332
Related