R Tutorial
Fundamentals of R
Variables
Input and Output
Decision Making
Control Flow
Functions
Strings
Vectors
Lists
Arrays
Matrices
Factors
DataFrames
Object Oriented Programming
Error Handling
File Handling
Packages in R
Data Interfaces
Data Visualization
Statistics
Machine Learning with R
Both matrices and data frames are fundamental data structures in R, and while they share some similarities, they have distinct characteristics and use-cases. This overview will help you differentiate between matrices and data frames in R:
Homogeneity vs. Heterogeneity:
Dimension:
Matrix:
my_matrix <- matrix(1:9, nrow = 3)
Data frame:
my_dataframe <- data.frame(column1 = c(1, 2, 3), column2 = c("A", "B", "C"))
Matrix: You can use numeric or boolean indexing for both rows and columns.
my_matrix[2, 3] # Element from 2nd row and 3rd column
Data frame: Supports $
indexing by column name in addition to numeric and boolean indexing.
my_dataframe$column1 # Accessing the 'column1' my_dataframe[, "column2"] # Another way to access the 'column2'
Matrix: Matrix-specific operations, like matrix multiplication, can be performed.
matrix1 %*% matrix2 # Matrix multiplication
Data frame: Operations are usually column-based, and many standard functions like mean()
, sum()
, etc., will work on data frames, but the operations are applied column-wise.
Understanding the differences between matrices and data frames helps in making informed decisions on which data structure to use based on the specific requirements of your data analysis or computations in R.