R How to Convert a Matrix to the data.frame Class (Example Code)
In this tutorial you’ll learn how to switch from matrix to data.frame class in the R programming language.
Creation of Example Data
example_matrix <- matrix(11:30, ncol = 5) # Creating matrix in R example_matrix # Showing example matrix in RStudio # [,1] [,2] [,3] [,4] [,5] # [1,] 11 15 19 23 27 # [2,] 12 16 20 24 28 # [3,] 13 17 21 25 29 # [4,] 14 18 22 26 30 |
example_matrix <- matrix(11:30, ncol = 5) # Creating matrix in R example_matrix # Showing example matrix in RStudio # [,1] [,2] [,3] [,4] [,5] # [1,] 11 15 19 23 27 # [2,] 12 16 20 24 28 # [3,] 13 17 21 25 29 # [4,] 14 18 22 26 30
Example: Apply as.data.frame() Function to Create Data Frame from Matrix
example_data_frame <- as.data.frame(example_matrix) # Changing matrix to data.frame class example_data_frame # Showing data frame in RStudio console # V1 V2 V3 V4 V5 # 1 11 15 19 23 27 # 2 12 16 20 24 28 # 3 13 17 21 25 29 # 4 14 18 22 26 30 |
example_data_frame <- as.data.frame(example_matrix) # Changing matrix to data.frame class example_data_frame # Showing data frame in RStudio console # V1 V2 V3 V4 V5 # 1 11 15 19 23 27 # 2 12 16 20 24 28 # 3 13 17 21 25 29 # 4 14 18 22 26 30
Related Articles
You may find some further tutorials in the following list: