In this post lets see few basic functions to deal with matrix creation and manipulation.
# Lets assume we wish to convert existing vector v into matrix m
v <- 1:12
# Lets create matrix m from elements of v with 3 row and 4 columns
m <- matrix(v, 3, 4)
# Declare matrix with all 0 values
m <- matrix(0, 3, 4)
# values 11, 12, 13, 14, 15 in all rows
m <- matrix(11:15, 5, 4)
# Check dimensions of given matrix
dim(m)
# Total number of elements in a matrix
length(m)
# Display 4-th row and all columns
m[4, ]
# Display 3-rd column and all rows
m[ ,3]
# Select first 3 rows and 3 columns
m[1:3,1:3]
# Select all columns but only 1st, 3rd and 5th row
row <- c(1,3,5)
m[ row,]
# Add new row r1 in existing matrix m1
m <- rbind(m1, r1)
# Add new column c1 in existing matrix m1
m <- cbind(m1, c1)
# Add two matrices m1 and m2 of same dimension
m2 + m1
# Subtract two matrices m2 and m1 of same dimension
m2 - m1
No comments:
Post a Comment