Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate mode in R but removing NA values

Tags:

r

na

mode

I am able to calculate the mode using

Mode <- function(x) {
 ux <- unique(x) 
tab <- tabulate(match(x, ux)); ux[tab == max(tab)]
}

However, my data frame has more NA values in it than integers so when I run this Mode, I get back NA.

Is there a way of removing NA values in the above function somehow or would I need to remove NA values from the dataframe initially? If so, how? I tried

DF.omit.NA<- na.omit(DF) ###and na.exclude

and it produced no rows of data.

like image 211
Bonono Avatar asked Sep 08 '25 01:09

Bonono


1 Answers

We can use na.omit wrapped around the unique elements

Mode <- function(x) {
  ux <- na.omit(unique(x) )
 tab <- tabulate(match(x, ux)); ux[tab == max(tab) ]
}

Mode(v1)
#[1] 1

data

v1 <- c(1, 3, NA, 2, 1, 1, NA, NA, NA)
like image 156
akrun Avatar answered Sep 09 '25 22:09

akrun