Comparison of data.frame() & as.data.frame() Functions in R (2 Examples)
In this R tutorial you’ll learn how to apply the data.frame and as.data.frame commands.
Example 1: Construct a New Data Frame Using the data.frame() Function
my_df_A <- data.frame(A = 4:1, # Constructing a data frame B = 1:4, C = "x") my_df_A # A B C # 1 4 1 x # 2 3 2 x # 3 2 3 x # 4 1 4 x |
my_df_A <- data.frame(A = 4:1, # Constructing a data frame B = 1:4, C = "x") my_df_A # A B C # 1 4 1 x # 2 3 2 x # 3 2 3 x # 4 1 4 x
Example 2: Transform a Matrix to a Data Frame Using the as.data.frame() Function
my_mat <- matrix(1:12, ncol = 4) # Constructing a matrix my_mat # Print matrix # [,1] [,2] [,3] [,4] # [1,] 1 4 7 10 # [2,] 2 5 8 11 # [3,] 3 6 9 12 |
my_mat <- matrix(1:12, ncol = 4) # Constructing a matrix my_mat # Print matrix # [,1] [,2] [,3] [,4] # [1,] 1 4 7 10 # [2,] 2 5 8 11 # [3,] 3 6 9 12
my_df_B <- as.data.frame(my_mat) # Converting a matrix to a data frame my_df_B # V1 V2 V3 V4 # 1 1 4 7 10 # 2 2 5 8 11 # 3 3 6 9 12 |
my_df_B <- as.data.frame(my_mat) # Converting a matrix to a data frame my_df_B # V1 V2 V3 V4 # 1 1 4 7 10 # 2 2 5 8 11 # 3 3 6 9 12