0

I am trying to calculate the increase in life expectancy for each country, but I cannot get the diff() function to work here. I also tried the lag/lead functions but I cannot use that. Any advise is appreciated.

library(gapminder)
gm <- gapminder
inclife <- gm %>%
   drop_na(lifeExp)%>%
   group_by(country) %>%
   select(country, year, lifeExp) %>%
   mutate(inc = diff(lifeExp))

This is the error I got

Error in `mutate()`:
! Problem while computing `inc = diff(lifeExp)`.
✖ `inc` must be size 12 or 1, not 11.
ℹ The error occurred in group 1: country = "Afghanistan".
Run `rlang::last_error()` to see where the error occurred.
Warsame
  • 69
  • 4

1 Answers1

5

Append a NA or another value, since diff will provide a vector of length n-1, and mutate requires that the number of observations does not change.

inclife <- gm %>%
   drop_na(lifeExp)%>%
   group_by(country) %>%
   select(country, year, lifeExp) %>%
   mutate(inc = c(NA,diff(lifeExp)))
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32