R Arrays
R Arrays
Example
1. #Creating two vectors of different lengths
2. vec1 <-c(1,3,5)
3. vec2 <-c(10,11,12,13,14,15)
4. #Taking these vectors as input to the array
5. res <- array (c (vec1, vec2), dim=c (3,3,2))
6. print(res)
#Array_name[row_possition,column_position,mattrix_level]
res[3,3,2]
res[3,1,1] #accesing individual element
res[1,,1] #accesing all columns in specific row
res[,2,1] #accesing all rows in specific column
res[,,1] #accesing all elements
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
1. #Creating two vectors of different lengths
2. vec1 <-c(1,3,5)
3. vec2 <-c(10,11,12,13,14,15)
4.
5. #Taking the vectors as input to the array1
6. res1 <- array(c(vec1,vec2),dim=c(3,3,2))
7. print(res1)
8.
9. #Creating two vectors of different lengths
10. vec1 <-c(8,4,7)
11. vec2 <-c(16,73,48,46,36,73)
12.
13. #Taking the vectors as input to the array2
14. res2 <- array(c(vec1, vec2),dim=c(3,3,2))
15. print(res2)
16.
17. #Creating matrices from these arrays
18. mat1 <- res1[,,2]
19. mat2 <- res2[,,2]
20. res3 <- mat1+mat2 #adding matrices
21. res4<-mat1-mat2 #subtracting matrices
22. res5<- mat1*mat2 #multiplying matrices
23. print(res3)
Example
#using apply function
output1<- apply(res,1, sum)
output 2 <- apply(res,1, mean)
output 3 <- apply(res,2, sd)
print(output 1)
print(output 2)
print(output 3)
Note: that if you’d like to find the mean or sum of each row, it faster to use the built-in
rowMeans() or rowSums()
Example
rowMeans(res)
rowSums(res)