Search notes:

R: data frames vs matrices

The following few R statements try to point out some differences between data frames and matrices. The script creates a data frame (df) and a matrix (mx) both of which have the same dimensions (3 columns times 2 rows) and the same data.
First, identical(df, mx) tells us that df is different from mx.
Then, the objects' attributes are determined with the respective function attributes(). It turns out that the data frame has the three attributes names, class and row.names while the matrix has only the single attribute dim.
Finally, applying length() on the objects returns 3 for the data frame, reflecting the three columns, and 6 for the matrix, reflecting the number of elements in the matrix.
df <- data.frame (
  col_1 = c(  2 ,  3 ),
  col_2 = c(  5 ,  7 ),
  col_3 = c( 11 , 13 )
);

mx <- matrix(
        c(2, 3, 5, 7, 11, 13),
        nrow=2
      );

df
#
#   col_1 col_2 col_3
# 1     2     5    11
# 2     3     7    13

mx
#
#      [,1] [,2] [,3]
# [1,]    2    5   11
# [2,]    3    7   13

identical(df, mx)
#
# [1] FALSE

attributes(df)
#
# $names
# [1] "col_1" "col_2" "col_3"
#
# $class
# [1] "data.frame"
#
# $row.names
# [1] 1 2

attributes(mx)
#
# $dim
# [1] 2 3

length(df)
#
# [1] 3

length(mx)
#
# [1] 6
Github repository about-r, path: /data-structures/data-frame_vs_matrix/basic.R

Conversion from data frame to matrix

Because a data frame might contain different data types but a matrix is constrained to a single data type, the conversion from a data frame to a matrix coerces all values of the data frame to the same data type in the matrix.

Index