查找序数中位数的惯用方法
我需要在 R 中找到序数(即有序因子)的中位数。
我在标准库中找不到执行此操作的方法,因此我想出了以下笨重的解决方案:
ordinal.median <- function(x){
lbls <- levels(x)
new.vars <- c(NA, 1:length(lbls))
new.vars[1] <- median(as.numeric(x))
return(factor(new.vars, labels=lbls, ordered=T)[1])
}
What would be the idiomatic Solution to this在 R 中?
I need to find the median of an ordinal (i.e. ordered factor) in R.
I couldn't find a method in the standard library to do this, so I came up with the following clunky solution:
ordinal.median <- function(x){
lbls <- levels(x)
new.vars <- c(NA, 1:length(lbls))
new.vars[1] <- median(as.numeric(x))
return(factor(new.vars, labels=lbls, ordered=T)[1])
}
What would be the idiomatic solution to this in R?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以稍微简化一下(请注意,
ordered
是序数因子的类,因此您可以仅使用median(o)
来调用它,其中o 是你的变量):
用法:
You can simplify it a bit (and note that
ordered
is the class for ordinal factors, so you can call this with justmedian(o)
whereo
is your variable):Usage:
有关
type=
选项的讨论,请参阅帮助页面。See help page for discussion of the
type=
option.