Finding the most common element

Original source:

Want to learn more? I recommend working through: R for Data Science, R Cookbook, and R Graphics Cookbook.

# Create a list of wars
wars <- c("Spanish Civil War", "Spanish Civil War", "Spanish Civil War", "Spanish Civil War", "WWII", "WWII")
# Create a function that finds the most common element in an object
most.common <- function(x) {
  count <- sapply(unique(x), function(i) sum(x==i, na.rm=TRUE))
# Run the function on the list of wars
[1] "Spanish Civil War"