Trying to display NONE when there is no mode in R

℡╲_俬逩灬. 提交于 2019-12-13 01:43:17

问题


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.

examples:

{1,1,2,2,3} Expected results 1 2(success)

{NA,NA,NA,1,1,1,3,3} Expected results NA 1(success)

{1,2,3,4,5} Expected result NONE (success)

{1,1,1,1,1} Expected result 1 (fail)

EDIT: 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])
}

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.

EDIT: I DID IT

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])
}

回答1:


How about this:

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

It's a slight modification of Ken William's Mode function in this answer.



来源:https://stackoverflow.com/questions/48269237/trying-to-display-none-when-there-is-no-mode-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!