You are on page 1of 2

#Matrices - R objects in which the elements of the same atomic type

#are arranged in a two dimensional rectangular layout.


#usually used in mathematical calculations

#the basic syntax is matrix(data, nrow, ncolumn, byrow, dimnames)


#The following attributes are used
#data- input vector which become the data elements
#nrow - number of rows
#ncol - number of column
#byrow - logical clue
#dimnames - names assigned to rows and columns

#Creating and naming matrices


#Create a 2-by-3 matirx with values 1 to 6 and 2 rows
matrix(1:6, nrow=2)

#Create a 2-by-3 matirx with values 1 to 6 and 2 columns


matrix(1:6, ncol = 2)

#Fill up the matrix in row wise fashion


matrix (1:6, nrow =2, byrow= TRUE)

#can also use cbind and rbind function


cbind(1:3, 1:3)

rbind(1:3,1:3)

m<- matrix(1:6, nrow=2, byrow = TRUE)


rbind(m, 7:9)

cbind(m, c(10,11))

#naming the matrix


#weuse rownames() and colnames()
m<- matrix(1:6, nrow=2, byrow = TRUE)

rownames(m)<- c("row1", "row2")


colnames(m)<- c ("col1", "col2", "col3")
#Option 2
m1<- matrix(1:6, nrow=2, byrow = TRUE, dimnames = list(c("row1", "row2"),c ("col1",
"col2", "col3")))
#matrix subsetting
m<- matrix(sample(1:15,12), nrow = 3)
m
#will print an element after counting column wise
m[9]
m[4]
#will print an element in the second row and third column
m[2,3]
#print element in thirs row second column
m[3,2]
#print only the third column
m[,3]
#print only the third row
m[3,]
#ARRAY
#option1 for assigning names
mn<- array(1:24,c(2,3,3),dimnames =
list(c("r1","r2"),c("c1","c2","c3"),c("m1","m2","m3")))
#option 2 for assigning names
RN<- c("r1","r2")
CN<- c("c1","c2","c3")
MN<-c("m1","m2","m3")
mn1<- array(1:24,c(2,3,3),dimnames = list(RN,CN,MN))

#Array Subsetting
#get the element in the first row, third column, third matrix
mn[1,3,3]
mn["r1","c3","m3"]
#get the second column in the second matrix, check if the result is an array
mn[,2,2]
is.array(mn[,2,2])
#use drop=FALSE to ensure the result is an array
mn[,2,2,drop=FALSE]
is.array(mn[,2,2,drop=F])
#access only the second matrix
mn[,,"m2"]

#perform arithmetic operations between the elements of matrices


#multiply the elements on the second row second column 2nd matrix
#with the elements of the second row third column third matrix
mn[2,2,2]*mn[2,3,3]
#ensure that the result is an array
mn[2,2,2,drop=FALSE]*mn[2,3,3]
is.array(mn[2,2,2,drop=FALSE]*mn[2,3,3])
#divide the elements of the second matrix with that of the elements on the first
matrix
mn[,,2]/mn[,,1]

#----------------
#Factors - Categorical data
bloodgroup<- c("A",'B','O','AB','AB','O','A')
BG<- factor(bloodgroup,levels=c("B","O","AB","A"), labels=c("BG_B",
"BG_O","BG_AB","BG_A"))

#For ordered factors


BG<- factor(bloodgroup,ordered = TRUE, levels=c("B","O","AB","A"), labels =
c("BG_B","BG_O","BG_AB","BG_A"))
BG
str(BG)

BG[1]<BG[2]
BG[2]<BG[1]

You might also like