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.
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!
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
.
> combn(1:3, 2)
[,1] [,2] [,3]
[1,] 1 1 2
[2,] 2 3 3
> apply(combn(1:3, 2), 2, function(x) mat[, x[1]]/mat[,x[2]] )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.