You are on page 1of 5

Arrays in R

What is an array?
• Arrays are the R data objects which can store
data in more than two dimensions.

• For example, if there is an array of dimension


(2,3,4), means that there are four matrices
each of dimension 2x3.

• It is created using array() function.


Creating array from vectors
#creating array from vectors
v1 <- c(1,2,3)
v2 <- c(4,5,6,7,8,9)
A1 <- array(c(v1,v2),dim = c(3,3,2))
A1

#naming columnes and rows


rname <- c("r1","r2","r3")
cname <- c("c1","c2","c3")
mname <- c("mat1","mat2")
A1 <- array(c(v1,v2),dim = c(3,3,2),dimnames =
list(rname,cname,mname))
A1
Accessing Array Elements
#printing the second row of second matrix
A1[2,,2]

#printin the second column of first matrix


A1[,2,1]

#printing the element in the 2nd row and 3rd


column of second matrix
A1[2,3,2]

#printing the second matrix


A1[,,2]
Manipulating Arrays
#Manipulating array elements
M1 <- A1[,,1]
M2 <- A1[,,2]
M3 <- M1+M2
M3

#Aggregation on array elements


apply(A1,1,sum) #1- along row
apply(A1,2,sum) #2 -along column
apply(A1,2,mean)

You might also like