在 R 中没有模式时尝试显示 NONE [英] Trying to display NONE when there is no mode in R
问题描述
我试图找出数据集的模式,如果没有模式,则显示NONE".我目前正在使用 Gregor 的功能,如下所述.
I am trying to figure the mode of a data set, while displaying "NONE" if there is no mode. I am currently using Gregor's function as commented below.
示例:
{1,1,2,2,3}预期结果 1 2
(成功)
{1,1,2,2,3}
Expected results 1 2
(success)
{NA,NA,NA,1,1,1,3,3}预期结果 NA 1
(成功)
{NA,NA,NA,1,1,1,3,3}
Expected results NA 1
(success)
{1,2,3,4,5}预期结果 NONE
(成功)
{1,2,3,4,5}
Expected result NONE
(success)
{1,1,1,1,1}预期结果 1
(失败)
{1,1,1,1,1}
Expected result 1
(fail)
我正在尝试使用 if...and 函数,因为我意识到似乎存在一些逻辑问题.但我似乎无法破解它
I am trying out with if...and functions, as I realize there seems to be some logical problems. But I can't seem to crack it
smode<-function(x,...) {
ux <- unique(x)
tx <- tabulate(match(x, ux))
if(((unique(x)>=2)&(length(unique(tx)) == 1)) {
return("NONE")
}
max_tx <- tx == max(tx)
return(ux[max_tx])
}
现在,{1,1,1,1,1,1} 或任何其他类似的东西只显示 NONE
再次检查,{1,1,1,2,2,2} 也显示 NONE
而不是 1 2
Right now, {1,1,1,1,1,1} or any other alike just displays NONE
Just checked again, and {1,1,1,2,2,2} displays NONE
too instead of 1 2
我假设对于更相似的事情,它会是一样的.
I'm assuming it will be the same for more similiar things.
我做到了
function(x,...) {
ux <- unique(x)
tx <- tabulate(match(x, ux))
if(sum(tx)/length(tx) == 1) {
return("NONE")
}
max_tx <- tx == max(tx)
return(ux[max_tx])
}
推荐答案
这个怎么样:
Mode <- function(x) {
ux <- unique(x)
tx <- tabulate(match(x, ux))
if(length(unique(tx)) == 1) {
message("None")
return(NA)
}
max_tx <- tx == max(tx)
return(ux[max_tx])
}
Mode(1:5)
# None
# [1] NA
Mode(c(1, 1, 2, 3))
# [1] 1
Mode(c(1, 1, 2, 2, 3))
# [1] 1 2
Mode(c(1, 1, 2, 2, 3, 3))
# None
# [1] NA
这是对 Ken William 的 Mode
函数在这个答案中的轻微修改.
It's a slight modification of Ken William's Mode
function in this answer.
这篇关于在 R 中没有模式时尝试显示 NONE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!