Reshape Array to Data Frame in R (Example Code)
This article demonstrates how to reshape an array object to a data frame in the R programming language.
Creation of Example Data
x <- array(11:22, dim = c(3, 2, 2)) # Construct example array x # , , 1 # # [,1] [,2] # [1,] 11 14 # [2,] 12 15 # [3,] 13 16 # # , , 2 # # [,1] [,2] # [1,] 17 20 # [2,] 18 21 # [3,] 19 22 |
x <- array(11:22, dim = c(3, 2, 2)) # Construct example array x # , , 1 # # [,1] [,2] # [1,] 11 14 # [2,] 12 15 # [3,] 13 16 # # , , 2 # # [,1] [,2] # [1,] 17 20 # [2,] 18 21 # [3,] 19 22
Example: Converting an Array to a Data Frame
df <- as.data.frame.table(x) # Switch from array to data frame class df # Var1 Var2 Var3 Freq # 1 A A A 11 # 2 B A A 12 # 3 C A A 13 # 4 A B A 14 # 5 B B A 15 # 6 C B A 16 # 7 A A B 17 # 8 B A B 18 # 9 C A B 19 # 10 A B B 20 # 11 B B B 21 # 12 C B B 22 |
df <- as.data.frame.table(x) # Switch from array to data frame class df # Var1 Var2 Var3 Freq # 1 A A A 11 # 2 B A A 12 # 3 C A A 13 # 4 A B A 14 # 5 B B A 15 # 6 C B A 16 # 7 A A B 17 # 8 B A B 18 # 9 C A B 19 # 10 A B B 20 # 11 B B B 21 # 12 C B B 22
Further Resources & Related Articles
Below, you may find some additional resources on topics such as time objects, matrices, and data conversion: