Calculating the ratio between the average engine life expectancies

Viewed 37

I have a small R dataframe below containing cars made in Japan and in Mexico from 2006 to 2008. I need to calculate the ratio between the average engine life for the cars built in Japan and Mexico for each year. I am using dplyr and so far I have been able to group by year and place built.

However I am stuck in this part. Any idea how I can calculate the ratio between the average engine life for cars built in Japan and Mexico for each year?

Here is the code I used:

cars_df %>%
    group_by(year_built, place_built) %>%
    summarise(car,year_built,place_built, 
               avg_life_exp = mean(engine_life_expectancy))

example dataframe

1 Answers

After we create the 'engine_life_expectancy', do a mutate. The summarise by default drop the last grouping column. So, now, it is grouped by 'year_built', thus we can divide the first element of 'avg_life_exp' by the last or the second

library(dplyr)
cars_df %>%
     group_by(car, year_built, place_built) %>%  
     summarise(avg_life_exp = mean(engine_life_expectancy)) %>%
     mutate(ratio = first(avg_life_exp)/last(avg_life_exp)) 

NOTE: Instead of specifying 'car' in the summarise (as summarise from the new version can return multiple rows for each group), we can include the 'car' also as a grouping column

Related