有没有更好的方法来创建分位数“虚拟”? / R 中的因子?

发布于 2024-09-28 18:50:02 字数 549 浏览 0 评论 0原文

我想指定代表分位数的因子。因此我需要它们是数字。 这就是为什么我编写了以下函数,这基本上是我的问题的答案:

qdum <- function(v,q){

qd = quantile(v,1:(q)/q)
v = as.data.frame(v)
v$b = 0
names(v) <- c("a","b")
i=1
for (i in 1:q){

    if(i == 1)
        v$b[ v$a < qd[1]] = 1
    else
        v$b[v$a > qd[i-1] & v$a <= qd[i]] = i
}

all = list(qd,v)
return(all)

    }

你现在可能会笑:)。 返回的列表包含一个变量,可用于将每个观察值分配给其相应的分位数。我现在的问题是:有没有更好的方法(更“原生”或“核心”)来做到这一点?我知道 quantcut (来自 gtools 包),但至少根据我得到的参数,我最终只得到了那些不方便的(? - 至少对我来说)阈值。

任何有助于变得更好的反馈都将受到赞赏!

i´d like to assign factors representing quantiles. Thus I need them to be numeric.
That´s why I wrote the following function, which is basically the answer to my problem:

qdum <- function(v,q){

qd = quantile(v,1:(q)/q)
v = as.data.frame(v)
v$b = 0
names(v) <- c("a","b")
i=1
for (i in 1:q){

    if(i == 1)
        v$b[ v$a < qd[1]] = 1
    else
        v$b[v$a > qd[i-1] & v$a <= qd[i]] = i
}

all = list(qd,v)
return(all)

    }

you may laugh now :) .
The returned list contains a variable that can be used to assign every observation to its corresponding quantile. My question is now: is there a better way (more "native" or "core") to do it? I know about quantcut (from the gtools package), but at least with the parameters I got, I ended up with only with those unhandy(? - at least to me) thresholds.

Any feedback thats helps to get better is appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅唱々樱花落 2024-10-05 18:50:02

使用基数 R,使用分位数来计算分割,然后将数字变量转换为离散变量:

qcut <- function(x, n) {
  cut(x, quantile(x, seq(0, 1, length = n + 1)), labels = seq_len(n),
    include.lowest = TRUE)
}

或者如果您只想要数字:

qcut2 <- function(x, n) {
  findInterval(x, quantile(x, seq(0, 1, length = n + 1)), all.inside = T)
}

With base R, use quantiles to figure out the splits and then cut to convert the numeric variable to discrete:

qcut <- function(x, n) {
  cut(x, quantile(x, seq(0, 1, length = n + 1)), labels = seq_len(n),
    include.lowest = TRUE)
}

or if you just want the number:

qcut2 <- function(x, n) {
  findInterval(x, quantile(x, seq(0, 1, length = n + 1)), all.inside = T)
}
晨敛清荷 2024-10-05 18:50:02

我不确定 quantcut 是什么,但我会执行以下操作

qdum <- function(v, q) {
 library(Hmisc)
 quantilenum <- cut2(v, g=q)
 levels(quantilenum) <- 1:q
 cbind(v, quantilenum)
}

I'm not sure what quantcut is but I would do the following

qdum <- function(v, q) {
 library(Hmisc)
 quantilenum <- cut2(v, g=q)
 levels(quantilenum) <- 1:q
 cbind(v, quantilenum)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文