How to Access and Manipulate the elements of Array in R?

Accessing array elements

Like C or C++, we can access the elements of the array. The elements are accessed with the help of the index. Simply, we can access the elements of the array with the help of the indexing method. Let see an example to understand how we can access the elements of the array using the indexing method.

Example

, , Matrix1  
     Col1 Col2 Col3  
Row1    1   10   13  
Row2    3   11   14  
Row3    5   12   15  
  
, , Matrix2  
     Col1 Col2 Col3  
Row1    1   10   13  
Row2    3   11   14  
Row3    5   12   15  
  
Col1 Col2 Col3  
   5   12   15  
  
[1] 13  
  
     Col1 Col2 Col3  
Row1    1   10   13  
Row2    3   11   14  
Row3    5   12   15  

Manipulation of elements

The array is made up matrices in multiple dimensions so that the operations on elements of an array are carried out by accessing elements of the matrices.

Example

#Creating two vectors of different lengths  
vec1 <-c(1,3,5)  
vec2 <-c(10,11,12,13,14,15)  
  
#Taking the vectors as input to the array1   
res1 <- array(c(vec1,vec2),dim=c(3,3,2))  
print(res1)  
  
#Creating two vectors of different lengths  
vec1 <-c(8,4,7)  
vec2 <-c(16,73,48,46,36,73)  
  
#Taking the vectors as input to the array2   
res2 <- array(c(vec1,vec2),dim=c(3,3,2))  
print(res2)  
  
#Creating matrices from these arrays  
mat1 <- res1[,,2]  
mat2 <- res2[,,2]  
res3 <- mat1+mat2  
print(res3)  

Output

, , 1
     [,1] [,2] [,3]
[1,]    1   10   13
[2,]    3   11   14
[3,]    5   12   15

, , 2
     [,1] [,2] [,3]
[1,]    1   10   13
[2,]    3   11   14
[3,]    5   12   15

, , 1
     [,1] [,2] [,3]
[1,]    8   16   46
[2,]    4   73   36
[3,]    7   48   73

, , 2
     [,1] [,2] [,3]
[1,]    8   16   46
[2,]    4   73   36
[3,]    7   48   73


     [,1] [,2] [,3]
[1,]    9   26   59
[2,]    7   84   50
[3,]   12   60   88

Calculations across array elements

For calculation purpose, r provides apply() function. This apply function contains three parameters i.e., x, margin, and function.

This function takes the array on which we have to perform the calculations. The basic syntax of the apply() function is as follows:

apply(x, margin, fun)

Here, x is an array, and a margin is the name of the dataset which is used and fun is the function which is to be applied to the elements of the array.

Example

#Creating two vectors of different lengths  
vec1 <-c(1,3,5)  
vec2 <-c(10,11,12,13,14,15)  
  
#Taking the vectors as input to the array1   
res1 <- array(c(vec1,vec2),dim=c(3,3,2))  
print(res1)  
  
#using apply function   
result <- apply(res1,c(1),sum)  
print(result)    

Output

, , 1
     [,1] [,2] [,3]
[1,]    1   10   13
[2,]    3   11   14
[3,]    5   12   15

, , 2
     [,1] [,2] [,3]
[1,]    1   10   13
[2,]    3   11   14
[3,]    5   12   15

[1] 48 56 64