r matrix in r

In R, a matrix is a collection of elements of the same data type organized into a fixed number of rows and columns. To create a matrix in R, you can use the matrix() function.

Here's an example of creating a matrix with 3 rows and 4 columns:

main.r
# Create a matrix
my_matrix <- matrix(1:12, nrow = 3, ncol = 4)

# Print the matrix
my_matrix
94 chars
6 lines
main.r
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
100 chars
5 lines

You can access elements of a matrix using indexing. To access the element in the second row and third column of my_matrix:

main.r
# Access an element of the matrix
my_matrix[2, 3]  # returns 8
63 chars
3 lines

You can also access entire rows or columns of a matrix using a single index:

main.r
# Access an entire row of the matrix
my_matrix[1, ]  # returns 1 4 7 10

# Access an entire column of the matrix
my_matrix[, 3]  # returns 7 8 9
145 chars
6 lines

To find out the dimensions of a matrix, you can use the dim() function:

main.r
# Get the dimensions of the matrix
dim(my_matrix)  # returns 3 4
65 chars
3 lines

You can modify elements of a matrix using indexing:

main.r
# Modify an element of the matrix
my_matrix[2, 3] <- 20
my_matrix
66 chars
4 lines
main.r
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5   20   11
[3,]    3    6    9   12
100 chars
5 lines

gistlibby LogSnag