If you want to read the original article, click here Convert data frame to array in R.
Are you looking for the latest Data Science Job Vacancies / Internship then click here finnstats.
We encourage that you read this article from finnstats to stay up to date..
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.
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.
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.
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.
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!.
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.
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!
To read more visit Convert data frame to array in R.
If you are interested to learn more about data science, you can find more articles here finnstats.