有没有更好的方法来创建分位数“虚拟”? / R 中的因子?
我想指定代表分位数的因子。因此我需要它们是数字。 这就是为什么我编写了以下函数,这基本上是我的问题的答案:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用基数 R,使用分位数来计算分割,然后将数字变量转换为离散变量:
或者如果您只想要数字:
With base R, use quantiles to figure out the splits and then cut to convert the numeric variable to discrete:
or if you just want the number:
我不确定 quantcut 是什么,但我会执行以下操作
I'm not sure what quantcut is but I would do the following