How to Divide Matrix Rows by a Vector in R (Example Code)
In this tutorial you’ll learn how to use the t() function to divide rows by a vector in the R programming language.
my_matrix <- matrix(11:30, ncol = 5) # Example matrix in R my_matrix # Display example matrix in RStudio console # [,1] [,2] [,3] [,4] [,5] # [1,] 11 15 19 23 27 # [2,] 12 16 20 24 28 # [3,] 13 17 21 25 29 # [4,] 14 18 22 26 30 |
my_matrix <- matrix(11:30, ncol = 5) # Example matrix in R my_matrix # Display example matrix in RStudio console # [,1] [,2] [,3] [,4] [,5] # [1,] 11 15 19 23 27 # [2,] 12 16 20 24 28 # [3,] 13 17 21 25 29 # [4,] 14 18 22 26 30
my_vector <- 5:1 # Example vector in R my_vector # Display example vector in RStudio console # [1] 5 4 3 2 1 |
my_vector <- 5:1 # Example vector in R my_vector # Display example vector in RStudio console # [1] 5 4 3 2 1
Example: Dividing Rows of Matrix by Vector Elements Using t() Function
t(t(my_matrix) / my_vector) # Applying t() function # [,1] [,2] [,3] [,4] [,5] # [1,] 2.2 3.75 6.333333 11.5 27 # [2,] 2.4 4.00 6.666667 12.0 28 # [3,] 2.6 4.25 7.000000 12.5 29 # [4,] 2.8 4.50 7.333333 13.0 30 |
t(t(my_matrix) / my_vector) # Applying t() function # [,1] [,2] [,3] [,4] [,5] # [1,] 2.2 3.75 6.333333 11.5 27 # [2,] 2.4 4.00 6.666667 12.0 28 # [3,] 2.6 4.25 7.000000 12.5 29 # [4,] 2.8 4.50 7.333333 13.0 30
Related Articles
Please find some further R tutorials on topics such as extracting data, vectors, and matrices in the following list.