Let's say I have the following data.frame. I'd like to replace the NA with the most commonly occurring response, a
df <- read.table(text = "id result
1 a
2 a
3 a
4 b
5 NA", header = T)
I'm looking for something like this:
calculate_mode <- function(x) {
uniqx <- unique(x)
uniqx[which.max(tabulate(match(x, uniqx)))]
}
df = df %>%
mutate(result = ifelse(is.na(result), calculate_mode(result), result))
But I'm not sure if there is a more "tidy" way of doing this outside defining a custom function.