2013-07-11 133 views
1

我有一個46175 * 741矩陣。我想要獲得每一行的四分位數。基於這個問題(How to create a column with a quartile rank?), 我想:矩陣中的每一行得到四分位數R

dat_quartiles <- apply(t(dat) , 1, function(x) within(x, as.integer(cut(x, quantile(x, probs=0:4/4), include.lowest=TRUE)))) 

但我得到的錯誤:

Error in UseMethod("within") : no applicable method for 'within' applied to an object of class "c('integer', 'numeric')" 

確切位置在哪裏我要去錯了嗎?

回答

4

我可能會過分解讀你正在嘗試做的,但是這owuld是我能想到的返回每一行的四分位數爲矩陣的最簡單的方法:

mat <- matrix(rnorm(1000), 100,10) 
apply(mat, 1, quantile) 

要分配分位數:

quantfun <- function(x) as.integer(cut(x, quantile(x, probs=0:4/4), include.lowest=TRUE)) 
apply(mat, 1, quantfun) 
+0

是的,我已經這樣做了,但我希望它告訴我,如果它的第一個四分位數或第二個等,而不是每行的確切數字。 – cianius

+0

@pepsimax - 現在應該工作。如果你只是對結果值感興趣,那麼你不需要「內部」。 –

+0

我有非唯一值,所以要讓你的代碼工作,我必須使用獨特的(分位數......)。非常感謝馬克!這不是你第一次幫助我:) – cianius