I wanted to define a function in R to find out the mode of a vector. I made a simple one which is shown below:
modeFinder <- function(par) {
modeTable <- par %>% table() %>% sort(decreasing = TRUE) %>% data.frame()
modeVal <- modeTable$Var1[1] %>% as.character()
return(modeVal)
}
However, when I use this function it always returns empty values. I actually wanted to use this for my summarize function but it doesn't work. I tried to diagnose by segregating the steps like below and it works completely fine that way!
# let's assume a vector "Vic" with expected output "m"
Vic <- c(rep("m", 3), rep("g", 2))
temp <- Vic %>% table() %>% sort(decreasing = TRUE) %>% data.frame()
temp2 <- temp$Var1[1] %>% as.character()
I just can't understand why the custom function is not working while the same code is working outside the function.
I would really appreciate any solution to this. Thanks!
EDIT: I think my question is not clear to some. I just want to know what the problem is in my custom function. I am not looking for any inbuilt function or an alternative to this.