Site icon R-bloggers

R Matrix

[This article was first published on R feed, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

A matrix is a two-dimensional data structure where data are arranged into rows and columns. For example,

{IMAGE: 2 * 3 matrix with integer data}

Here, the above matrix is 2 * 3 (pronounced "two by three") matrix because it has 2 rows and 3 columns.


Create a Matrix in R

In R, we use the matrix() function to create a matrix.

The syntax of the matrix() function is

matrix(vector, nrow, ncol)

Here,

Let's see an example,

# create a 2 by 3 matrix
matrix1 <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)

print(matrix1)

Output

    [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

In the above example, we have used the matrix() function to create a matrix named matrix1.

matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)

Here, we have passed data items of integer type and used c() to combine data items together. And nrow = 2 and ncol = 3 means the matrix has 2 rows and 3 columns.

Since we have passed byrow = TRUE, the data items in the matrix are filled row-wise. If we didn't pass byrow argument as

matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)

The output would be

    [,1]  [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

Access Matrix Elements in R

We use the vector index operator [ ] to access specific elements of a matrix in R.

The syntax to access a matrix element is

matrix[n1, n2]

Here,

Let's see an example,

matrix1 <- matrix(c("Sabby", "Cathy", "Larry", "Harry"), nrow = 2, ncol = 2)

print(matrix1)

# access element at 1st row, 2nd column
cat("\nDesired Element:", matrix1[1, 2])

Output

      [,1]          [,2]   
[1,] "Sabby" "Larry"
[2,] "Cathy" "Harry"

Desired Element: Larry

In the above example, we have created a 2 by 2 matrix named matrix1 with 4 string type datas. Notice the use of index operator [],

matrix1[1, 2]

Here, [1, 2] specifies we are trying to access element present at 1st row, 2nd column i.e. "Larry".

Access Entire Row or Column

In R, we can also access the entire row or column based on the value passed inside [].

For example,

matrix1 <- matrix(c("Sabby", "Cathy", "Larry", "Harry"), nrow = 2, ncol = 2)

print(matrix1)

# access entire element at 1st row
cat("\n1st Row:", matrix1[1, ])

# access entire element at 2nd column
cat("\n2nd Column:", matrix1[, 2])

Output

       [,1]         [,2]   
[1,] "Sabby" "Larry"
[2,] "Cathy" "Harry"

1st Row: Sabby Larry
2nd Column: Larry Harry

Here,

Access More Than One Row or Column

We can access more than one row or column in R using the c() function.

For example,

# create 2 by 3 matrix
matrix1 <- matrix(c(10, 20, 30, 40, 50, 60), nrow = 2, ncol = 3)

print(matrix1)

# access entire element of 1st and 3rd row
cat("\n1st and 2nd Row:", matrix1[c(1,3), ])

# access entire element of 2nd and 3rd column
cat("\n2nd and 3rd Column:", matrix1[  ,c(2,3)])

Output

       [,1] [,2]  [,3]
[1,]   10   30   50
[2,]   20   40   60

1st and 3rd Row: 10 20 30 40 50 60
2nd and 3rd Column: 30 40 50 60

Here,


Modify Matrix Element in R

We use the vector index operator [] to modify the specified element. For example,

matrix1[1,2] = 140

Here, the element present at 1st row, 2nd column is changed to 140.

Let's see an example,

# create 2 by 2 matrix
matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2)

# print original matrix
print(matrix1)

# change value at 1st row, 2nd column to 5 
matrix1[1,2] = 5

# print updated matrix
print(matrix1)

Output

    [,1] [,2]
[1,]    1    3
[2,]    2    4

     [,1] [,2]
[1,]    1    5
[2,]    2    4

Combine Two Matrices in R

In R, we use the cbind() and the rbind() function to combine two matrices together.

The number of rows and columns of two matrices we want to combine must be equal. For example,

# create two 2 by 2 matrices 
even_numbers <- matrix(c(2, 4, 6, 8), nrow = 2, ncol = 2)
odd_numbers <- matrix(c(1, 3, 5, 7), nrow = 2, ncol = 2)

# combine two matrices by column
total1 <- cbind(even_numbers, odd_numbers)
print(total1)

# combine two matrices by row
total2 <- rbind(even_numbers, odd_numbers)
print(total2)

Output

    [,1] [,2] [,3] [,4]
[1,]    2    6    1    5
[2,]    4    8    3    7
     [,1] [,2]
[1,]    2    6
[2,]    4    8
[3,]    1    5
[4,]    3    7

Here, first we have used the cbind() function to combine the two matrices: even_numbers and odd_numbers by column. And rbind() to combine two matrices by row.


Check if Element Exists in R Matrix

In R, we use the %in% operator to check if the specified element is present in the matrix or not and returns a boolean value.

For example,

matrix1 <- matrix(c("Sabby", "Cathy", "Larry", "Harry"), nrow = 2, ncol = 2)

"Larry" %in% matrix1 # TRUE

"Kinsley" %in% matrix1 # FALSE

Output

TRUE
FALSE

Here,


To leave a comment for the author, please follow the link and comment on their blog: R feed.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.