【问题标题】:get quartile for every row in matrix R获取矩阵 R 中每一行的四分位数
【发布时间】:2013-07-09 18:05:40
【问题描述】:

我有一个 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')"

我到底哪里错了?

【问题讨论】:

    标签: r


    【解决方案1】:

    我可能对您正在尝试做的事情了解太多,但这应该是我能想到的返回矩阵中每一行的四分位数的最简单方法:

    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)
    

    【讨论】:

    • 是的,我首先这样做了,但我希望它告诉我是第一个四分位数还是第二个等,而不是每行的确切数字。
    • @pepsimax - 现在应该可以工作了。如果您只对结果值感兴趣,则不需要within
    • 我有非唯一值,所以为了让你的代码工作,我必须使用唯一(分位数...)。感谢一百万,虽然马克!这不是你第一次帮助我 :)
    猜你喜欢
    • 2011-10-15
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2023-03-21
    • 2016-01-28
    相关资源
    最近更新 更多