How to Convert Data Frame to matrix Class in R (Example Code)
This tutorial shows how to change a data object from data.frame to matrix class in the R programming language.
Construction of Example Data
example_data_frame <- data.frame(col1 = 1:4, # Creating example frame col2 = 4:1, col3 = 5:8, col4 = 1) example_data_frame # Showing data frame in console # col1 col2 col3 col4 # 1 1 4 5 1 # 2 2 3 6 1 # 3 3 2 7 1 # 4 4 1 8 1 |
example_data_frame <- data.frame(col1 = 1:4, # Creating example frame col2 = 4:1, col3 = 5:8, col4 = 1) example_data_frame # Showing data frame in console # col1 col2 col3 col4 # 1 1 4 5 1 # 2 2 3 6 1 # 3 3 2 7 1 # 4 4 1 8 1
Example: Applying as.matrix() Function to Change data.frame to matrix Class
example_matrix <- as.matrix(example_data_frame) # Change data.frame to matrix example_matrix # Showing matrix in console # col1 col2 col3 col4 # [1,] 1 4 5 1 # [2,] 2 3 6 1 # [3,] 3 2 7 1 # [4,] 4 1 8 1 |
example_matrix <- as.matrix(example_data_frame) # Change data.frame to matrix example_matrix # Showing matrix in console # col1 col2 col3 col4 # [1,] 1 4 5 1 # [2,] 2 3 6 1 # [3,] 3 2 7 1 # [4,] 4 1 8 1
Related Tutorials & Further Resources
You may find some further R programming tutorials on topics such as time objects, numeric values, and character strings in the following list: