得到矩阵R中每一行的四分位数

时间:2013-07-11 12:51:17

标签: r

我有一个46175 * 741矩阵。我想为每一行获得四分位数。基于这个问题(How to create a column with a quartile rank?), 我试过了:

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')"

我到底哪里错了?

1 个答案:

答案 0 :(得分:4)

我可能正在阅读你想要做的事情,但这本来是我能想到的最简单的方法,用于返回矩阵中每行的四分位数:

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)