Copy and paste the following code to your R Studio platform or R version:

# Matrices in R

?matrix

mat1 <- matrix(c(10, 9, 8, 7, 6, 5), nrow = 3, ncol = 2, byrow = TRUE)
# apparently the number of elements in the vector should be equal to the
# number we obtain when we multiply the nrow with the ncol number

print(mat1)
View(mat1)

# Accessing the matrix elements
mat1[2,2] # row, column in the matrix
mat1[3,1]
mat1[2, c(1,2)] # go to the second row and print the elements 1 and 2

mat2 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2, byrow = FALSE)
mat2

mat3 <- matrix(c(1:9), nrow = 3, ncol = 3, byrow = TRUE)
mat3
mat3[ ,3]
mat3[2, ]
mat3[ ,c(1,3)]

my.data <- 1:20
my.data

A <- matrix(my.data, 4, 5)
A
A[2,3]

B <- matrix(my.data, 4, 5, byrow = TRUE)
B
B[2,5]

 

# rbind()

r1 <- c(“I”, “am”, “happy”)
r2 <- c(“What”, “a”, “day”)
r3 <- c(1, 2, 3)
C <- rbind(r1, r2, r3)
C

# cbind()

c1 <- 1:5
c2 <- -1:-5
D <- cbind(c1, c2)
D
D[1,2]

# Named vectors

Charlie <- 1:5
Charlie

names(Charlie)
names(Charlie) <- c(“N1”, “N2”, “N3”, “N4”, “N5”)
Charlie
Charlie[“N4”]
names(Charlie)

# Clear names

names(Charlie) <- NULL
Charlie

# Naming matrix dimensions

temp.vec <- rep(c(“James”, “Harvey”, “Alan”), each = 3)
# instead of times, we replicate the names 3 times each
temp.vec

bravo <- matrix(temp.vec, nrow = 3, ncol = 3)
bravo

row.names(bravo) <- c(“First”, “Second”, “Third”)
colnames(bravo) <- c(“Name1”, “Name2”, “Name3”)
bravo
bravo[“First”, ]
row.names(bravo)
bravo[“Third”, “Name1”] <- “Denny”
bravo

# Matrix Operations
mat3
mat3 <- mat3 – 1
mat3

# checking the dimensions of a matrix
dim(mat3) # number of rows and columns

mat2

mat4 <- mat2 + mat3
# not the same number of rows and columns in the individual matrices
mat4 <- mat3 + mat3
mat4

# interchanging the rows and columns in a matrix is known as transpose
print(mat4)
mat5 <- t(mat4)
mat5

# combining matrices:
# columnwise, only when we have the same number of rows
# rowise, only when we have the same number of columns

mat6 <- matrix(c(10, 11, 12), nrow = 3, ncol = 1)
mat6

combined.c <- cbind(mat5, mat6)
combined.c

combined.r <- rbind(mat4, mat5)
combined.r

Posted by Dimitris

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s