R: mean of all cases with a certain factor level

Viewed 56

I try the code from here Mean by factor by level but it does not work. Here is my situation. From the flights dataset, I want to know the average flight delay of all planes from the carrier UA.

library(nycflights13)
data(flights)
mean(flights$air_time[flights$carrier == "UA"])

But what results is just

[1] NA

What did I do wrong?

3 Answers

Since there are missing values (NA) in the dataset, you need to specify the argument na.rm = TRUE within the mean function. Otherwise, if at least one value is NA, the mean function (as well as other functions like sum, min, max, ...) will return NA.

mean(flights$air_time[flights$carrier == "UA"], na.rm = TRUE)
# [1] 211.7914

If you are looking for the mean time for flights$carrier == "UA", you could try a solution in dplyr by using summarise

This solution takes missing values into account by na.rm=TRUE

library(dplyr)
flights %>% 
  filter(carrier == "UA") %>%
  summarise(., mean(air_time, na.rm=TRUE))

As Ric S says, use na.rm = TRUE and keep in mind that when R finds NA values, functions will use it as the main value, so you might have similar problems using many other similar functions such as median, max, min, etc.

Related