# Convert data frame to array in R

Convert data frame to array in R, A data frame is a table or a two-dimensional array-like structure in which each column has the values of a single variable and each row holds one set of values from each column.

## Data Frame

A data frame has the following qualities.

1. The column names should not be blank.

2. Row names should be distinct.

3. A data frame can store data that is numeric, factored, or character-based.

4. The number of data items in each column should be the same.

## Array

R data objects that can store data in more than two dimensions are called arrays. When we generate an array of dimension (2, 3, 4) for example, we get four rectangular matrices, each with two rows and three columns.

Arrays can only store data types.

Conditional Mean in R with examples » finnstats

The array() function is used to create an array. It takes vectors as input and creates an array using the values in the dim argument.

For this R programming course, the following data is utilized as a starting point,

df1 <- data.frame(x = 1:5, y = 5:1) df1

x y 1 1 5 2 2 4 3 3 3 4 4 2 5 5 1

Now we can create another data frame.

Significance of Spearman’s Rank Correlation » finnstats

df2 <- data.frame(x = 11:15,y = 15:11) df2

x y 1 11 15 2 12 14 3 13 13 4 14 12 5 15 11

We have produced two data frames with the same row and column names, but different values, as shown in df1 and df2.

Let’s make an array out of these data frames!.

Correlation Analysis Different Types of Plots in R » finnstats

### Approach: Convert data frame to array in R

Using the array() function, save data frames in an array object.

In the R programming language, this example shows how to generate an array from two input data frames.

We can utilize the array, c, unlist, list, rownames, and colnames functions to do this work, as illustrated below.

How to Generate Kernel Density Plots in R » finnstats

Array1 <- array(data = c(unlist(df1), unlist(df2)), dim = c(5, 2, 2), dimnames = list(rownames(df1), colnames(df1))) Array1

, , 1 x y 1 1 5 2 2 4 3 3 3 4 4 2 5 5 1 , , 2 x y 1 11 15 2 12 14 3 13 13 4 14 12 5 15 11

The preceding R syntax built a new array called Array1 that contains our two input data frames, as you can see.

Subscribe to our newsletter!