Ethan
Ethan

Reputation: 13

Calculate quantile for a whole matrix

For the working purposes, I need to find the overall quantile cut points for a matrix. I know I can "unlist" or "break" the matrix into two dimensional column and R can easily apply "quantile" function for a vector.

However, once I unlist the matrix and calculate the quantile, I don't know how to recover the unlisted data to the original one. Can someone tell me a method that can achieve this? Or are there some alternative ways to achieve my purpose?

Upvotes: 1

Views: 4293

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145755

You don't seem very clear on your data structures. If you actually have an object of class matrix there is no need to unlist or anything else, you can call quantile directly on a matrix:

> m = matrix(1:100, nrow = 10)
> quantile(m, probs = c(.25, .5, .75))
  25%   50%   75% 
25.75 50.50 75.25 

If you have a data.frame, then you do need to unlist (or convert to matrix with as.matrix), but you do not need to overwrite your saved data frame.

> my_df = data.frame(c1 = 1:5, c2 = 11:15)
> quantile(unlist(my_df), probs = c(.25, .5, .75))
  25%   50%   75% 
 3.25  8.00 12.75 
> my_df
  c1 c2
1  1 11
2  2 12
3  3 13
4  4 14
5  5 15

Notice at the end that my_df is still a data frame. As long as you don't re-assign my_df with the unlisted version, it will not be changed.

Upvotes: 4

Related Questions