0

I have the following code but don't fully understand it, as I am relatively new to R.

mode <- function(x){
  ta<-table(x)
  tam <- max(ta)
  if (all(ta==tam))
    mod <- NA
  else if(is.numeric(x))
    mod <- as.numeric(names(ta)[ta==tam])
  else
    mod <- names(ta)[ta==tam]
  return(mod)
}

Can someone please explain what is happening under the else if and else segments of the code?

Thanks!

Rachel
  • 21
  • 2
  • Related to https://stackoverflow.com/questions/31400445/r-how-to-find-the-mode-of-a-vector – akrun Jan 13 '22 at 18:39
  • Here is a function that is little more straightforward: https://stackoverflow.com/a/8189441/15293191 – AndrewGB Jan 13 '22 at 18:41
  • 1) if all of the counts are the same as the max count, then the mode is NA (this doesnt make sense to me but it's not wrong per se); 2) is coercing the table names from strings back to numeric if the original vector was numeric (this also seems clumsy as it would depend on number of digits used for the names); 3) if x was not numeric (ie, string, factor, logical, etc), just return the table name with the highest count – rawr Jan 13 '22 at 18:55

0 Answers0