Matrix element division in R
Solution 1
What you actually have there is a data frame. It's essentially a matrix, you're right, but you access the columns by using the column's names.
Accessing each column of the data frame can be done through a command like this:
Matrix$close
This should give you the desired data frame, if I understood your question correctly.
New_DataFrame <- data.frame(close = Matrix$close / (Matrix$close.1 * Matrix$close.2), close.1 = Matrix$close.1 / Matrix$close.2)
These operations are all done in respect to each individual row.
If you want your answer in the form of a matrix instead of a data frame, use this:
New_Matrix <- data.matrix(New_DataFrame)
And switching back to a data frame from a matrix is as easy as:
New_DataFrame <- data.frame(New_Matrix)
Hope that helps!
Solution 2
If mat
is your matrix, then mat[,1]/mat[,2]
gives you the element-wise division of each row. If mat
is actually a data.frame not a matrix, then the above works, as does mat$close/mat$close.1
.
floorscrapers
Updated on November 22, 2022Comments
-
floorscrapers over 1 year
I have a Matrix:
close close.1 close.2 1 38.050 22.320 23.115 2 37.650 22.150 23.055 3 37.295 22.090 23.090
And I would like to divide "close" by "close.1", "close" by "close.2" and finally "close.1" by "close.2" for each row.
I'm aware that I can write a horrible looking for loop that would solve this but I would be really grateful to know if there was an easy way to do this in R ?
Any help would be greatly appreciated.
Thanks.
-
Ben Bolker almost 12 years
with
makes this more compact:New_Matrix <- with(Matrix, data.frame(close1 = close/close.1, close2 = close/close.2, close12 = close/(close.1*close.2)))