# How to Convert R List to Array

Array in R is a list or vector with two or more dimensions. An array is like a stacked matrix, and a matrix is a two-dimensional array. List in R is a specific data type of vector that can store mixed types.

## Convert R List to Array

To convert list to array in R, use the array() function with as.numeric() and unlist() function. The unlist() function produces a vector that contains all the atomic components in the list. The as.numeric() function converts the factorial value to numeric value in R. The code snippet for converting R List to Array is the following.

### Code snippet

``array(as.numeric(unlist(data)), dim=c(x, y, z))``

The as.numeric() function takes two parameters

1. data: It is a list which we will unlist using the unlist() method.
2. dim: It is the dimension for the output array. It takes rows(x), columns(y), and a number of matrices of dimensions nrow * ncol(z).

To convert a list to an array, we need to create a list, and to create a list, we need to define vectors. Let’s define four vectors.

``````rv1 <- 1:5
rv2 <- 6:10
rv3 <- 11:15
rv4 <- 16:20``````

To create a list from vectors, use the list() function and pass the vectors in the argument.

``````rv1 <- 1:5
rv2 <- 6:10
rv3 <- 11:15
rv4 <- 16:20

data <- list(rv1, rv2, rv3, rv4)
data``````

#### Output

``````[]
 1 2 3 4 5

[]
 6 7 8 9 10

[]
 11 12 13 14 15

[]
 16 17 18 19 20``````

You can see that we have successfully created a list out of the vectors.

The next step is to use the combination of unlist(), as.numeric(), and array() function to convert list to an array.

``````rv1 <- 1:5
rv2 <- 6:10
rv3 <- 11:15
rv4 <- 16:20

data <- list(rv1, rv2, rv3, rv4)
arr <- array(as.numeric(unlist(data)), dim = c(5, 4, 2))
arr``````

#### Output

``````, , 1

[,1] [,2] [,3] [,4]
[1,]  1    6    11   16
[2,]  2    7    12   17
[3,]  3    8    13   18
[4,]  4    9    14   19
[5,]  5   10    15   20

, , 2

[,1] [,2] [,3] [,4]
[1,]  1    6   11    16
[2,]  2    7   12    17
[3,]  3    8   13    18
[4,]  4    9   14    19
[5,]  5   10   15    20``````

Here, we have created a 5 x 4 array with 2 times the number of matrices. The array() function creates or tests for arrays. It takes data and dimension as parameters and returns the specified dimensional array. An array in R can have one, two, or more dimensions.

That is it for the casting list to array tutorial.