Matrices in R

Learn about matrices and how to manipulate them using R.

Working with matrices

Matrices are two-dimensional data containers in R. We can define matrices using the matrix() function. They have columns and rows and thus can be addressed, selected, filtered, and modified. The elements of matrices are always the same data type. Even if the elements are initially from different data types, they converge into one common data type when they gather in a matrix. Recall that this functionality is the same as that for the vector objects.

Press + to interact

Notably, a default matrix structure is composed of one column, but we can split the initial column into multiple parts using the nrow= or ncol= arguments. The total number of matrix elements equals the number of rows times the number of columns. Therefore, the values chosen for the arguments should be the multipliers of the total number of matrix elements.

Press + to interact
# Create a default matrix
print('Initial Matrix')
myMatrix <- matrix(1:9) # Define a matrix
print(myMatrix) # Print the matrix
print('--------------------------------------------------')
print('Row number is defined')
myMatrix <- matrix(1:9, nrow = 3) # Define a matrix
print(myMatrix) # Print the matrix
print(typeof(myMatrix)) # Show the data type of the matrix elements
print('--------------------------------------------------')
# Create multiple columns
print('The matrix contains different data types')
myMatrix <- matrix(c(1,2,3,TRUE,4,FALSE,5,'Code',9), nrow = 3) # Define a matrix
print(myMatrix) # Print the matrix
print(typeof(myMatrix)) # Show the data type of the matrix elements

Notice the types of the second and the third matrices (lines 9 and 15) in the code block above. The units in the third matrix converge in the character data type since it is the type ...

Get hands-on with 1400+ tech skills courses.