We’ll illustrate measures of central tendency with the msleep dataset that comes from tidyverse. msleep contains some data about how much different kinds of mammals sleep. Here’s what the first few rows of msleep look like.
msleep |>head()
# A tibble: 6 × 11
name genus vore order conservation sleep_total sleep_rem sleep_cycle awake
<chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 Cheetah Acin… carni Carn… lc 12.1 NA NA 11.9
2 Owl mo… Aotus omni Prim… <NA> 17 1.8 NA 7
3 Mounta… Aplo… herbi Rode… nt 14.4 2.4 NA 9.6
4 Greate… Blar… omni Sori… lc 14.9 2.3 0.133 9.1
5 Cow Bos herbi Arti… domesticated 4 0.7 0.667 20
6 Three-… Brad… herbi Pilo… <NA> 14.4 2.2 0.767 9.6
# ℹ 2 more variables: brainwt <dbl>, bodywt <dbl>
Mean
The mean is a variable’s average value.
It can be computed in two ways:
by summing all observations together using sum(), then dividing by the total number of observations n()
by using the mean() function
For example, to find the mean hours of sleep in msleep:
mean() worked for sleep_total, but if we try it with sleep_rem (hours of REM sleep), we get “NA” instead of a number.
msleep |>summarise(mean_REM =mean(sleep_rem) )
# A tibble: 1 × 1
mean_REM
<dbl>
1 NA
This is because the data has not recorded the REM sleep for every animal. Where the hours of REM sleep are unknown, the data contains the value NA. NA stands for “not available”. And any NAs in this variable will make the mean() function return NA instead of an actual number.
To force mean() to overlook the NAs and return the mean of all the values we do have, use the code na.rm = TRUE (na.rm stands for “NA remove”).