-1

In my R class, we are currently learning how to manipulate Tibbles. I have a homework problem where I need to grab the life expectancy from 1952 for a country and compare it to all its other expectancies for however many years of data the tibble has. For all countries within the table, in one line using pipes.

Background: this table is called gap

I have used the line:

gap %>% group_by(year, lifeExp) %>% filter(year == 1952) 

To filter out the lifeExp for all countries during 1952, but from there I have no idea how to pipe back into the table and compare those initial values to the other specific country values. I know what all the basic dplyr functions do, just having trouble seeing the bigger picture with all the pipes.

If this wasn't enough to understand, I will edit! Thank you for any kind of support!

1 Answers1

1

You can solve it with the help of mutate and match.

library(dplyr)

gapminder::gapminder %>% 
  group_by(country) %>% 
  mutate(difference = lifeExp - lifeExp[match(1952, year)]) %>%
  ungroup -> gap

gap

#   country     continent  year lifeExp      pop gdpPercap difference
#   <fct>       <fct>     <int>   <dbl>    <int>     <dbl>      <dbl>
# 1 Afghanistan Asia       1952    28.8  8425333      779.       0   
# 2 Afghanistan Asia       1957    30.3  9240934      821.       1.53
# 3 Afghanistan Asia       1962    32.0 10267083      853.       3.20
# 4 Afghanistan Asia       1967    34.0 11537966      836.       5.22
# 5 Afghanistan Asia       1972    36.1 13079460      740.       7.29
# 6 Afghanistan Asia       1977    38.4 14880372      786.       9.64
# 7 Afghanistan Asia       1982    39.9 12881816      978.      11.1 
# 8 Afghanistan Asia       1987    40.8 13867957      852.      12.0 
# 9 Afghanistan Asia       1992    41.7 16317921      649.      12.9 
#10 Afghanistan Asia       1997    41.8 22227415      635.      13.0 
# … with 1,694 more rows
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213