R Arrays


Arrays

Compared to matrix, the same members can have more than two sizes.

We can use the array() function to create a list, and a dim parameter to specify a size:


Example
# An array with one dimension with values ranging from 1 to 24
thisarray <- c(1:24)
thisarray

# An array with more than one dimension
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray

Example Explained

In the example above we create a list of numbers 1 to 24.

How does dim = c (4,3,2) work?

The first and second numbers in parentheses determine the number of rows and columns.

The last number in parentheses indicates how many values ​​we want.

Note: Lists can contain only one type of data.



Access Array Items

You can access the elements of the same members by referring to the index area. You can use [] brackets to access the desired elements in the list:


Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))

multiarray[2, 3, 2]

The syntax is as follows: list [row location, column location, matrix level]


You can also access the entire row or column from the matrix in the list, using the function c():


Example
thisarray <- c(1:24)

# Access all the items from the first row from matrix one
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray[c(1),,1]

# Access all the items from the first column from matrix one
multiarray <- array(thisarray, dim = c(4, 3, 2))
multiarray[,c(1),1]

The comma (,) before c () indicates that we want to reach the column.

The comma (,) after c () indicates that we want to reach the line.



Check if an Item Exists

To find out if something is listed, use %in% operator:


Example

Check if the value "2" is present in the array:

thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))

2 %in% multiarray


Amount of Rows and Columns

Use the dim() function to find the number of rows and columns in an order:


Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))

dim(multiarray)


Array Length

Use the length() function to find the size of the same member:


Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))

length(multiarray)


Loop Through an Array

You can access the program properties via for loop:


Example
thisarray <- c(1:24)
multiarray <- array(thisarray, dim = c(4, 3, 2))

for(x in multiarray){
  print(x)
}