Save Data Frames as Array Object in R (Example Code)

In this R tutorial you’ll learn how to convert data frames to an array.

Creating Example Data

df_A <- data.frame(col1 = 6:2,                                         # Construct three data frames
                   col2 = 7:3,
                   col3 = 3)
df_A
#   col1 col2 col3
# 1    6    7    3
# 2    5    6    3
# 3    4    5    3
# 4    3    4    3
# 5    2    3    3
df_B <- data.frame(col1 = 2:6,
                   col2 = 3:7,
                   col3 = 5)
df_B
#   col1 col2 col3
# 1    2    3    5
# 2    3    4    5
# 3    4    5    5
# 4    5    6    5
# 5    6    7    5
df_C <- data.frame(col1 = 1:5,
                   col2 = 1,
                   col3 = 2)
df_C
#   col1 col2 col3
# 1    1    1    2
# 2    2    1    2
# 3    3    1    2
# 4    4    1    2
# 5    5    1    2

Example: Transform Data Frame Objects to Array

df_array <- array(data = c(unlist(df_A), unlist(df_B), unlist(df_C)),  # Construct array
                  dim = c(5, 3, 3), 
                  dimnames = list(rownames(df_A), colnames(df_A)))
df_array
# , , 1
# 
#   col1 col2 col3
# 1    6    7    3
# 2    5    6    3
# 3    4    5    3
# 4    3    4    3
# 5    2    3    3
# 
# , , 2
# 
#   col1 col2 col3
# 1    2    3    5
# 2    3    4    5
# 3    4    5    5
# 4    5    6    5
# 5    6    7    5
# 
# , , 3
# 
#   col1 col2 col3
# 1    1    1    2
# 2    2    1    2
# 3    3    1    2
# 4    4    1    2
# 5    5    1    2

Related Articles

Have a look at the following R tutorials. They illustrate topics such as time objects, matrices, and factors.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top