## ── Attaching packages ────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 3.2.1 ✔ purrr 0.2.5
## ✔ tibble 2.0.1 ✔ dplyr 0.8.0.1
## ✔ tidyr 0.8.1 ✔ stringr 1.4.0
## ✔ readr 1.1.1 ✔ forcats 0.3.0
## ── Conflicts ───────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library(stringr)
Nat0306 <- read_delim("~/Dropbox/RProjects/Fertility Study/Nat0306.txt","\t", escape_double = FALSE)## Parsed with column specification:
## cols(
## Notes = col_character(),
## State = col_character(),
## StateCode = col_character(),
## Age = col_character(),
## AgeCode = col_character(),
## Year = col_integer(),
## YearCode = col_integer(),
## Births = col_integer(),
## FPop = col_character(),
## Rate = col_character()
## )
## Warning in rbind(names(probs), probs_f): number of columns of result is not
## a multiple of vector length (arg 1)
## Warning: 66 parsing failures.
## row # A tibble: 5 x 5 col row col expected actual file expected <int> <chr> <chr> <chr> <chr> actual 1 1637 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na… file 2 1638 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na… row 3 1639 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na… col 4 1640 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na… expected 5 1641 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na…
## ... ................. ... ........................................................................... ........ ........................................................................... ...... ........................................................................... .... ........................................................................... ... ........................................................................... ... ........................................................................... ........ ...........................................................................
## See problems(...) for more details.
Nat0717 <- read_delim("~/Dropbox/RProjects/Fertility Study/Nat0717.txt","\t", escape_double = FALSE)## Parsed with column specification:
## cols(
## Notes = col_character(),
## State = col_character(),
## StateCode = col_character(),
## Age = col_character(),
## AgeCode = col_character(),
## Year = col_integer(),
## YearCode = col_integer(),
## Births = col_integer(),
## FPop = col_character(),
## Rate = col_character()
## )
## Warning in rbind(names(probs), probs_f): number of columns of result is not
## a multiple of vector length (arg 1)
## Warning: 73 parsing failures.
## row # A tibble: 5 x 5 col row col expected actual file expected <int> <chr> <chr> <chr> <chr> actual 1 4539 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na… file 2 4540 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na… row 3 4541 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na… col 4 4542 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na… expected 5 4543 <NA> 10 columns 1 columns '~/Dropbox/RProjects/Fertility Study/Na…
## ... ................. ... ........................................................................... ........ ........................................................................... ...... ........................................................................... .... ........................................................................... ... ........................................................................... ... ........................................................................... ........ ...........................................................................
## See problems(...) for more details.
Look at the data.
Select the variables we want. Convert the character variable Rate to numeric and eliminate the rows where this variable is na. Then combine the two dataframes using rbind.
We could probably do the rbind first and save a few lines of typing. Per-preocesing the two separate files eliminates the possibility of problems because of differences between these two files, which came from different queries.
Nat0306 %>%
select(State,Year,Age,Rate) %>%
mutate(Rate = as.numeric(Rate)) %>%
filter(!is.na(Rate)) -> Nat0306## Warning: NAs introduced by coercion
## Observations: 1,224
## Variables: 4
## $ State <chr> "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Al…
## $ Year <int> 2003, 2004, 2005, 2006, 2003, 2004, 2005, 2006, 2003, 2004…
## $ Age <chr> "15-19 years", "15-19 years", "15-19 years", "15-19 years"…
## $ Rate <dbl> 51.40, 51.02, 48.06, 51.83, 113.67, 113.48, 116.90, 121.36…
Nat0717 %>%
select(State,Year,Age,Rate) %>%
mutate(Rate = as.numeric(Rate)) %>%
filter(!is.na(Rate)) -> Nat0717## Warning: NAs introduced by coercion
## Observations: 3,366
## Variables: 4
## $ State <chr> "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Al…
## $ Year <int> 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016…
## $ Age <chr> "15-19 years", "15-19 years", "15-19 years", "15-19 years"…
## $ Rate <dbl> 52.07, 50.53, 48.30, 43.63, 40.53, 39.15, 34.32, 32.02, 30…
## State Year Age Rate
## Length:4590 Min. :2003 Length:4590 Min. : 3.93
## Class :character 1st Qu.:2006 Class :character 1st Qu.: 29.38
## Mode :character Median :2010 Mode :character Median : 60.67
## Mean :2010 Mean : 65.21
## 3rd Qu.:2014 3rd Qu.:102.11
## Max. :2017 Max. :184.05
Now create a new dataframe with one row for each combination of State and Year. Create the variable TFR.
both %>%
group_by(State,Year) %>%
summarize(TFR = 5*sum(Rate)/1000) %>%
ungroup() -> SYTFR
glimpse(SYTFR)## Observations: 765
## Variables: 3
## $ State <chr> "Alabama", "Alabama", "Alabama", "Alabama", "Alabama", "Al…
## $ Year <int> 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012…
## $ TFR <dbl> 1.92205, 1.91695, 1.93785, 2.00555, 2.04290, 2.02050, 1.94…
Let’s look at the results. First try side-by-side boxplots to look at the changes over time. Note that we have to cast Year as a factor to get our boxplots.
There are some distinct groups of years. For analysis purposes, I would group them as follows:
Probably the great recession caused a drop in the birth rate.
The next step in our analysis is to introduce per capita personal income data from the Bureau of Economic Analysis. This is available in the file CA1.csv in Moodle. Import this data.
## Parsed with column specification:
## cols(
## .default = col_character(),
## GeoFIPS = col_integer(),
## Region = col_integer(),
## LineCode = col_integer()
## )
## See spec(...) for full column specifications.
## Warning in rbind(names(probs), probs_f): number of columns of result is not
## a multiple of vector length (arg 1)
## Warning: 4 parsing failures.
## row # A tibble: 4 x 5 col row col expected actual file expected <int> <chr> <chr> <chr> <chr> actual 1 9595 GeoFI… an integ… Note: See the included footno… '~/Dropbox/RProjec… file 2 9596 GeoFI… an integ… CA1: Personal Income Summary:… '~/Dropbox/RProjec… row 3 9597 GeoFI… an integ… Last updated: November 17, 20… '~/Dropbox/RProjec… col 4 9598 GeoFI… an integ… Source: U.S. Department of Co… '~/Dropbox/RProjec…
Looking at the results of the import process, we can see that there are some invalid records at the bottom of the file. These can be eliminated by requiring that GeoFIPS be numeric. We also want to keep only the rows for statewide values. These can be indentified as having GeoName values containing the string “state”. The income data we want can be identified as having LineCode values of 3. In our output, we want only the name of the state and the income data in columns 8 through 54.
Use View
Now we need to remove the extra text from the variable State. All rows have a string " state total" and some have an asterisk. These are removed in separate steps. The asterisk needs two leading backslashes because it has special significance in regular expressions. This is called “escaping.”
Use View.
Now we need to use the gather function from tidyr to put the column names indicating years into a column named Year with the income values from those columns in a single column named PCInc. In addition, we need to make Year and PCInc numeric. We only want data for the years 2003 through 2015.
Look at the documentation on gather() in Chapter 12 of RFDS.
CA4 <- CA3 %>%
gather(Year,PCInc,-1) %>%
mutate(Year = as.numeric(Year),
PCInc = as.numeric(PCInc)) %>% filter(Year >= 2003)
glimpse(CA4)## Observations: 663
## Variables: 3
## $ State <chr> "Alabama", "Alaska", "Arizona", "Arkansas", "California", …
## $ Year <dbl> 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003…
## $ PCInc <dbl> 26513, 35591, 28166, 25467, 35234, 35132, 45468, 38187, 46…
Now we can join the fertility data with the income data and examine the relationship between the two.
## Joining, by = c("State", "Year")
## Observations: 663
## Variables: 4
## $ State <chr> "Alabama", "Alaska", "Arizona", "Arkansas", "California", …
## $ Year <dbl> 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003…
## $ PCInc <dbl> 26513, 35591, 28166, 25467, 35234, 35132, 45468, 38187, 46…
## $ TFR <dbl> 1.92205, 2.28325, 2.39805, 2.04710, 2.11665, 2.14480, 1.90…
We can now look at the relationship between per capita personal income and the TFR.
The plot suggests something counterituitive - Higher income leads to reduced fertility. This clashes with our explanation for the decline in fertility beginning with the great recession.
Let’s add time to this graphic by mapping color to Year.
It seems that there may be some correlation between time and our income variable. Review data on real personal income and the CPI in FRED. https://fred.stlouisfed.org/ is the link.
Let’s import the CPI data downloaded from FRED.
## Parsed with column specification:
## cols(
## Year = col_integer(),
## CPI = col_double()
## )
Now we need to join the CPI Data with AllData and adjust the per capita income data for inflation.
## Joining, by = "Year"
## Observations: 663
## Variables: 6
## $ State <chr> "Alabama", "Alaska", "Arizona", "Arkansas", "Californi…
## $ Year <dbl> 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, …
## $ PCInc <dbl> 26513, 35591, 28166, 25467, 35234, 35132, 45468, 38187…
## $ TFR <dbl> 1.92205, 2.28325, 2.39805, 2.04710, 2.11665, 2.14480, …
## $ CPI <dbl> 184, 184, 184, 184, 184, 184, 184, 184, 184, 184, 184,…
## $ RealPCInc <dbl> 144.0924, 193.4293, 153.0761, 138.4076, 191.4891, 190.…
Now redo the original scatterplot using the adjusted per capita income data.
There is still a counterintuitive relationship. How can we explain this?
Let’s repeat the previous graph with a facet by year.
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
Looking back at the side-by-side boxplot, recall the grouping we saw there.
We can use the case_when statement to develop a variable to capture this grouping.
AllData3 <- AllData2 %>%
mutate(Period = case_when(
.$Year < 2006 ~ "Early",
.$Year < 2009 ~ "Peak",
.$Year < 2012 ~ "Decline",
TRUE ~ "Late"),
Period = factor(Period,levels=c("Early","Peak","Decline","Late"))
)
str(AllData3)## Classes 'tbl_df', 'tbl' and 'data.frame': 663 obs. of 7 variables:
## $ State : chr "Alabama" "Alaska" "Arizona" "Arkansas" ...
## $ Year : num 2003 2003 2003 2003 2003 ...
## $ PCInc : num 26513 35591 28166 25467 35234 ...
## $ TFR : num 1.92 2.28 2.4 2.05 2.12 ...
## $ CPI : num 184 184 184 184 184 184 184 184 184 184 ...
## $ RealPCInc: num 144 193 153 138 191 ...
## $ Period : Factor w/ 4 levels "Early","Peak",..: 1 1 1 1 1 1 1 1 1 1 ...
Now we can repeat the plot above with these groupings. We can also do a simple smoothing plot using the new variable to distinguish among periods.
AllData3 %>% ggplot(aes(x=RealPCInc,y=TFR,color=Period)) + geom_point() +
geom_smooth() + facet_wrap(~Period)## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
Here is another look at this without a facet or the points.
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
Turning off the confidence interval shading might be better.
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
The impact of the peak years is clear. There is some separation of the curves for lower levels of RealPCInc, but the spearation is weaker at higher levles of RealPCInc.
Let’s try a regression model and include the factor Period. R will create dummy variables automatically to take care of the Period variable.
##
## Call:
## lm(formula = TFR ~ RealPCInc + Period, data = AllData3)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.39463 -0.10693 -0.02544 0.09289 0.53061
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.4110913 0.0401444 60.061 < 2e-16 ***
## RealPCInc -0.0021371 0.0002127 -10.047 < 2e-16 ***
## PeriodPeak 0.0802308 0.0199591 4.020 6.50e-05 ***
## PeriodDecline -0.0684196 0.0199052 -3.437 0.000625 ***
## PeriodLate -0.1215957 0.0188969 -6.435 2.38e-10 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.1735 on 658 degrees of freedom
## Multiple R-squared: 0.2809, Adjusted R-squared: 0.2765
## F-statistic: 64.26 on 4 and 658 DF, p-value: < 2.2e-16
Let’s look at a few specific states in specific years.
## Classes 'tbl_df', 'tbl' and 'data.frame': 663 obs. of 7 variables:
## $ State : chr "Alabama" "Alaska" "Arizona" "Arkansas" ...
## $ Year : num 2003 2003 2003 2003 2003 ...
## $ PCInc : num 26513 35591 28166 25467 35234 ...
## $ TFR : num 1.92 2.28 2.4 2.05 2.12 ...
## $ CPI : num 184 184 184 184 184 184 184 184 184 184 ...
## $ RealPCInc: num 144 193 153 138 191 ...
## $ Period : Factor w/ 4 levels "Early","Peak",..: 1 1 1 1 1 1 1 1 1 1 ...
AllData3 %>%
filter(State %in% c("Connecticut","Utah","Washington","Alabama"),
Year %in% c(2003,2008,2015)) %>%
select(State,Year, RealPCInc,TFR) %>%
arrange(State,Year)## # A tibble: 12 x 4
## State Year RealPCInc TFR
## <chr> <dbl> <dbl> <dbl>
## 1 Alabama 2003 144. 1.92
## 2 Alabama 2008 155. 2.02
## 3 Alabama 2015 160. 1.83
## 4 Connecticut 2003 247. 1.90
## 5 Connecticut 2008 284. 1.85
## 6 Connecticut 2015 290. 1.60
## 7 Utah 2003 139. 2.62
## 8 Utah 2008 158. 2.65
## 9 Utah 2015 166. 2.29
## 10 Washington 2003 187. 1.91
## 11 Washington 2008 208. 2.02
## 12 Washington 2015 219. 1.81
The striking fact is that the different states have very different numbers for both of these variables. Moreover, the differences persist over time.
To make the numbers more comparable and more suitable for model building we frequently recast them in terms of percentage change from a base period. Here the base period is 2003. We will carry this out in distinct steps.
Starting with AllData3, create a dataframe baseValues with the following variables.
State B_TFR - Value of TFR in 2003 B_RealPCInc - Value of RealPCInc in 2003
AllData3 %>%
filter(Year == 2003) %>%
mutate(B_TFR = TFR, B_RealPCInc = RealPCInc) %>%
select(State, B_TFR, B_RealPCInc) -> baseValues
glimpse(baseValues)## Observations: 51
## Variables: 3
## $ State <chr> "Alabama", "Alaska", "Arizona", "Arkansas", "Califor…
## $ B_TFR <dbl> 1.92205, 2.28325, 2.39805, 2.04710, 2.11665, 2.14480…
## $ B_RealPCInc <dbl> 144.0924, 193.4293, 153.0761, 138.4076, 191.4891, 19…
Join the baseValues table to AllData3 producing AllData4. Glimpse AllData4 to make sure it looks OK. In AllData4, create PD_RealPCInc PD_TFR. These are percentage differences from the base values.
## Joining, by = "State"
## Observations: 663
## Variables: 9
## $ State <chr> "Alabama", "Alaska", "Arizona", "Arkansas", "Califor…
## $ Year <dbl> 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003…
## $ PCInc <dbl> 26513, 35591, 28166, 25467, 35234, 35132, 45468, 381…
## $ TFR <dbl> 1.92205, 2.28325, 2.39805, 2.04710, 2.11665, 2.14480…
## $ CPI <dbl> 184, 184, 184, 184, 184, 184, 184, 184, 184, 184, 18…
## $ RealPCInc <dbl> 144.0924, 193.4293, 153.0761, 138.4076, 191.4891, 19…
## $ Period <fct> Early, Early, Early, Early, Early, Early, Early, Ear…
## $ B_TFR <dbl> 1.92205, 2.28325, 2.39805, 2.04710, 2.11665, 2.14480…
## $ B_RealPCInc <dbl> 144.0924, 193.4293, 153.0761, 138.4076, 191.4891, 19…
In AllData4, create PD_RealPCInc PD_TFR. These are percentage differences from the base values.
Examine the results Graphically. Your choice!