Matrices in R Programming
A matrix is a table of numbers. In math text, it is conventional to denote matrices with bold letters. For example, consider a matrix D of the prices of the securities on first three days of the week.
D =
64 31
65 28
66 35
This matrix is {3*2} matrix (pronounced "3 by 2") . The number of rows is given first, followed by the number of columns. The Matrix D shows that on the first day, the bond was worth $64 and the stock was worth $31. On the second day the bond was worth $65 and the stock $28. On the third day the bond was worth $66 and the stock $35.
With this data in place, we can answer many analytics questions considering someone was holding these assets in their portfolio. Let's learn how to use matrices in R and then how to perform statistical analysis on them.
Defining a Matrix in R
Let's say we have the above data in the form of a vector:
> price_data <- c(64,31,65,28,66,35)
We know that this data represents three rows with each row containing the bond price and the stock price. In R, we can use this vector to create a matrix using the matrix()
function as shown below:
#price data each number pair represents the bond an dstock price
price_data <- c(64,31,65,28,66,35)
#Create matrix of prices
price_matrix <- matrix(price_data, nrow=3,byrow=TRUE)
#print the matrix
price_matrix
This content is for paid members only.
Join our membership for lifelong unlimited access to all our data science learning content and resources.