简体   繁体   中英

How can I use mutate to find the difference between two years in one column of my dataframe?

Hi i am new to the tidyverse in R and trying to work on a project

My dataframe(ab):

 Year       Zip     Total_Population Median_Income      City State
1 2014      00601            18088         10833  Adjuntas    PR
2 2014      00602            40859         16353    Aguada    PR
3 2015      00603            53162         16323 Aguadilla    PR
4 2015      00606             6415         14138   Maricao    PR
5 2016      00610            28805         17265    Anasco    PR
6 2016      00612            66251         17752   Arecibo    PR

I have used mutate to create population to income ratio based on zip:

dmg_ratio <-  ab %>% filter(Year %in% c(2014,2015,2016,2017)) %>% 
  group_by(Zip) %>%
  mutate(Poptoincomeratio = Total_Population/Median_Income)

dmg_ratio

Output repex:

Year Zip           Total_Population Median_Income City      State Poptoincomeratio
 2014 ZCTA5 00601            18088         10833 Adjuntas    PR               1.67 
 2014 ZCTA5 00602            40859         16353 Aguada      PR               2.50 
 2015 ZCTA5 00601            53162         16323 Adjuntas    PR               3.26 

I want to find the difference in this newly created mutation(Poptoincomeratio) from 2014 to 2016 per zip code to understand if there has been any change in the population to income ratio over the years. How would I be able to do this?

Actually, there is a workaround for this, I assumed you have 'Poptoincomeratio' columns filled for every single year Then, try this

library(tidyr)
new_ab <- ab %>% select(-Total_Population ,-Median_Income ) %>% spread(Year,Poptoincomeratio)

After this, you can apply mutate again to get the difference between two years.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM