In the wake of the Great Recession of 2009, there has been a good deal of focus on employment statistics, one of the most important metrics policymakers use to gauge the overall strength of the economy. In the United States, the government measures unemployment using the Current Population Survey (CPS), which collects demographic and employment information from a wide range of Americans each month. In this exercise, we will employ the topics reviewed in the lectures as well as a few new techniques using the September 2013 version of this rich, nationally representative dataset (available online).
The observations in the dataset represent people surveyed in the September 2013 CPS who actually completed a survey. While the full dataset has 385 variables, in this exercise we will use a more compact version of the dataset, CPSData.csv, which has the following variables:
PeopleInHousehold: The number of people in the interviewee’s household.
Region: The census region where the interviewee lives.
State: The state where the interviewee lives.
MetroAreaCode: A code that identifies the metropolitan area in which the interviewee lives (missing if the interviewee does not live in a metropolitan area). The mapping from codes to names of metropolitan areas is provided in the file MetroAreaCodes.csv.
Age: The age, in years, of the interviewee. 80 represents people aged 80-84, and 85 represents people aged 85 and higher.
Married: The marriage status of the interviewee.
Sex: The sex of the interviewee.
Education: The maximum level of education obtained by the interviewee.
Race: The race of the interviewee.
Hispanic: Whether the interviewee is of Hispanic ethnicity.
CountryOfBirthCode: A code identifying the country of birth of the interviewee. The mapping from codes to names of countries is provided in the file CountryCodes.csv.
Citizenship: The United States citizenship status of the interviewee.
EmploymentStatus: The status of employment of the interviewee.
Industry: The industry of employment of the interviewee (only available if they are employed).
Load the dataset from CPSData.csv into a data frame called CPS, and view the dataset with the summary() and str() commands.
CPS<-read.csv("D:/Data/Unit1/CPSData.csv",header = TRUE,sep=",")
summary(CPS)
PeopleInHousehold Region State MetroAreaCode Age
Min. : 1.000 Midwest :30684 California :11570 Min. :10420 Min. : 0.00
1st Qu.: 2.000 Northeast:25939 Texas : 7077 1st Qu.:21780 1st Qu.:19.00
Median : 3.000 South :41502 New York : 5595 Median :34740 Median :39.00
Mean : 3.284 West :33177 Florida : 5149 Mean :35075 Mean :38.83
3rd Qu.: 4.000 Pennsylvania: 3930 3rd Qu.:41860 3rd Qu.:57.00
Max. :15.000 Illinois : 3912 Max. :79600 Max. :85.00
(Other) :94069 NA's :34238
Married Sex Education
Divorced :11151 Female:67481 High school :30906
Married :55509 Male :63821 Bachelor's degree :19443
Never Married:30772 Some college, no degree:18863
Separated : 2027 No high school diploma :16095
Widowed : 6505 Associate degree : 9913
NA's :25338 (Other) :10744
NA's :25338
Race Hispanic CountryOfBirthCode Citizenship
American Indian : 1433 Min. :0.0000 Min. : 57.00 Citizen, Native :116639
Asian : 6520 1st Qu.:0.0000 1st Qu.: 57.00 Citizen, Naturalized: 7073
Black : 13913 Median :0.0000 Median : 57.00 Non-Citizen : 7590
Multiracial : 2897 Mean :0.1393 Mean : 82.68
Pacific Islander: 618 3rd Qu.:0.0000 3rd Qu.: 57.00
White :105921 Max. :1.0000 Max. :555.00
EmploymentStatus Industry
Disabled : 5712 Educational and health services :15017
Employed :61733 Trade : 8933
Not in Labor Force:15246 Professional and business services: 7519
Retired :18619 Manufacturing : 6791
Unemployed : 4203 Leisure and hospitality : 6364
NA's :25789 (Other) :21618
NA's :65060
str(CPS)
'data.frame': 131302 obs. of 14 variables:
$ PeopleInHousehold : int 1 3 3 3 3 3 3 2 2 2 ...
$ Region : Factor w/ 4 levels "Midwest","Northeast",..: 3 3 3 3 3 3 3 3 3 3 ...
$ State : Factor w/ 51 levels "Alabama","Alaska",..: 1 1 1 1 1 1 1 1 1 1 ...
$ MetroAreaCode : int 26620 13820 13820 13820 26620 26620 26620 33660 33660 26620 ...
$ Age : int 85 21 37 18 52 24 26 71 43 52 ...
$ Married : Factor w/ 5 levels "Divorced","Married",..: 5 3 3 3 5 3 3 1 1 3 ...
$ Sex : Factor w/ 2 levels "Female","Male": 1 2 1 2 1 2 2 1 2 2 ...
$ Education : Factor w/ 8 levels "Associate degree",..: 1 4 4 6 1 2 4 4 4 2 ...
$ Race : Factor w/ 6 levels "American Indian",..: 6 3 3 3 6 6 6 6 6 6 ...
$ Hispanic : int 0 0 0 0 0 0 0 0 0 0 ...
$ CountryOfBirthCode: int 57 57 57 57 57 57 57 57 57 57 ...
$ Citizenship : Factor w/ 3 levels "Citizen, Native",..: 1 1 1 1 1 1 1 1 1 1 ...
$ EmploymentStatus : Factor w/ 5 levels "Disabled","Employed",..: 4 5 1 3 2 2 2 2 3 2 ...
$ Industry : Factor w/ 14 levels "Agriculture, forestry, fishing, and hunting",..: NA 11 NA NA 11 4 14 4 NA 12 ...
Among the interviewees with a value reported for the Industry variable, what is the most common industry of employment? Please enter the name exactly how you see it.
install.packages("dplyr")
library(dplyr)
sort(table(CPS$Industry)) %>% tail
#Educational and health services
Recall from the homework assignment “The Analytical Detective” that you can call the sort() function on the output of the table() function to obtain a sorted breakdown of a variable. For instance, sort(table(CPS$Region)) sorts the regions by the number of interviewees from that region.
Which state has the fewest interviewees?
sort(table(CPS$State))
#New Mexico
Which state has the largest number of interviewees?
sort(table(CPS$State))
#California
What proportion of interviewees are citizens of the United States?
(7073+116639)/(7073+7590+116639)
[1] 0.9421943
The CPS differentiates between race (with possible values American Indian, Asian, Black, Pacific Islander, White, or Multiracial) and ethnicity. A number of interviewees are of Hispanic ethnicity, as captured by the Hispanic variable. For which races are there at least 250 interviewees in the CPS dataset of Hispanic ethnicity? (Select all that apply.)
table(CPS$Race,CPS$Hispanic)
0 1
American Indian 1129 304
Asian 6407 113
Black 13292 621
Multiracial 2449 448
Pacific Islander 541 77
White 89190 16731
Which variables have at least one interviewee with a missing (NA) value? (Select all that apply.)
colSums(is.na(CPS))
PeopleInHousehold Region State MetroAreaCode Age
0 0 0 34238 0
Married Sex Education Race Hispanic
25338 0 25338 0 0
CountryOfBirthCode Citizenship EmploymentStatus Industry
0 0 25789 65060
Often when evaluating a new dataset, we try to identify if there is a pattern in the missing values in the dataset. We will try to determine if there is a pattern in the missing values of the Married variable. The function
is.na(CPS$Married)
returns a vector of TRUE/FALSE values for whether the Married variable is missing. We can see the breakdown of whether Married is missing based on the reported value of the Region variable with the function
table(CPS$Region, is.na(CPS$Married))
Which is the most accurate:
lapply(CPS[c('Region','Sex','Age','Citizenship')],
function(x) table(is.na(CPS$Married), x))
table(CPS$Region, is.na(CPS$Married))
table(CPS$Sex, is.na(CPS$Married))
table(CPS$Age, is.na(CPS$Married))
table(CPS$Citizenship, is.na(CPS$Married))
As mentioned in the variable descriptions, MetroAreaCode is missing if an interviewee does not live in a metropolitan area. Using the same technique as in the previous question, answer the following questions about people who live in non-metropolitan areas.
How many states had all interviewees living in a non-metropolitan area (aka they have a missing MetroAreaCode value)? For this question, treat the District of Columbia as a state (even though it is not technically a state).
table(CPS$State,is.na(CPS$MetroAreaCode))
FALSE TRUE
Alabama 1020 356
Alaska 0 1590
Arizona 1327 201
Arkansas 724 697
California 11333 237
Colorado 2545 380
Connecticut 2593 243
Delaware 1696 518
District of Columbia 1791 0
Florida 4947 202
Georgia 2250 557
Hawaii 1576 523
Idaho 761 757
Illinois 3473 439
Indiana 1420 584
Iowa 1297 1231
Kansas 1234 701
Kentucky 908 933
Louisiana 1216 234
Maine 909 1354
Maryland 2978 222
Massachusetts 1858 129
Michigan 2517 546
Minnesota 2150 989
Mississippi 376 854
Missouri 1440 705
Montana 199 1015
Nebraska 816 1133
Nevada 1609 247
New Hampshire 1148 1514
New Jersey 2567 0
New Mexico 832 270
New York 5144 451
North Carolina 1642 977
North Dakota 432 1213
Ohio 2754 924
Oklahoma 1024 499
Oregon 1519 424
Pennsylvania 3245 685
Rhode Island 2209 0
South Carolina 1139 519
South Dakota 595 1405
Tennessee 1149 635
Texas 6060 1017
Utah 1455 387
Vermont 657 1233
Virginia 2367 586
Washington 1937 429
West Virginia 344 1065
Wisconsin 1882 804
Wyoming 0 1624
#District of Columbia,New Jersey
How many states had all interviewees living in a metropolitan area? Again, treat the District of Columbia as a state.
#Alaska
Which region of the United States has the largest proportion of interviewees living in a non-metropolitan area?
tapply(is.na(CPS$MetroAreaCode), CPS$Region, mean) %>% sort
Northeast South West Midwest
0.2162381 0.2378440 0.2436628 0.3478686
While we were able to use the table() command to compute the proportion of interviewees from each region not living in a metropolitan area, it was somewhat tedious (it involved manually computing the proportion for each region) and isn’t something you would want to do if there were a larger number of options. It turns out there is a less tedious way to compute the proportion of values that are TRUE. The mean() function, which takes the average of the values passed to it, will treat TRUE as 1 and FALSE as 0, meaning it returns the proportion of values that are true. For instance, mean(c(TRUE, FALSE, TRUE, TRUE)) returns 0.75. Knowing this, use tapply() with the mean function to answer the following questions:
Which state has a proportion of interviewees living in a non-metropolitan area closest to 30%?
tapply(is.na(CPS$MetroAreaCode),CPS$State,mean)
Alabama Alaska Arizona Arkansas
0.25872093 1.00000000 0.13154450 0.49049965
California Colorado Connecticut Delaware
0.02048401 0.12991453 0.08568406 0.23396567
District of Columbia Florida Georgia Hawaii
0.00000000 0.03923092 0.19843249 0.24916627
Idaho Illinois Indiana Iowa
0.49868248 0.11221881 0.29141717 0.48694620
Kansas Kentucky Louisiana Maine
0.36227390 0.50678979 0.16137931 0.59832081
Maryland Massachusetts Michigan Minnesota
0.06937500 0.06492199 0.17825661 0.31506849
Mississippi Missouri Montana Nebraska
0.69430894 0.32867133 0.83607908 0.58132376
Nevada New Hampshire New Jersey New Mexico
0.13308190 0.56874530 0.00000000 0.24500907
New York North Carolina North Dakota Ohio
0.08060769 0.37304315 0.73738602 0.25122349
Oklahoma Oregon Pennsylvania Rhode Island
0.32764281 0.21821925 0.17430025 0.00000000
South Carolina South Dakota Tennessee Texas
0.31302774 0.70250000 0.35594170 0.14370496
Utah Vermont Virginia Washington
0.21009772 0.65238095 0.19844226 0.18131868
West Virginia Wisconsin Wyoming
0.75585522 0.29932986 1.00000000
Which state has the largest proportion of non-metropolitan interviewees, ignoring states where all interviewees were non-metropolitan?
#Montana
Codes like MetroAreaCode and CountryOfBirthCode are a compact way to encode factor variables with text as their possible values, and they are therefore quite common in survey datasets. In fact, all but one of the variables in this dataset were actually stored by a numeric code in the original CPS datafile.
When analyzing a variable stored by a numeric code, we will often want to convert it into the values the codes represent. To do this, we will use a dictionary, which maps the the code to the actual value of the variable. We have provided dictionaries MetroAreaCodes.csv and CountryCodes.csv, which respectively map MetroAreaCode and CountryOfBirthCode into their true values. Read these two dictionaries into data frames MetroAreaMap and CountryMap.
How many observations (codes for metropolitan areas) are there in MetroAreaMap?
MetroAreaMap<-read.csv("D:/Data/Unit1/MetroAreaCodes.csv", stringsAsFactors=F)
nrow(MetroAreaMap)
[1] 271
How many observations (codes for countries) are there in CountryMap?
CountryMap<-read.csv("D:/Data/Unit1/CountryCodes.csv", stringsAsFactors=F)
nrow(CountryMap)
[1] 149
To merge in the metropolitan areas, we want to connect the field MetroAreaCode from the CPS data frame with the field Code in MetroAreaMap. The following command merges the two data frames on these columns, overwriting the CPS data frame with the result:
CPS = merge(CPS, MetroAreaMap, by.x="MetroAreaCode", by.y="Code", all.x=TRUE)
The first two arguments determine the data frames to be merged (they are called “x” and “y”, respectively, in the subsequent parameters to the merge function). by.x=“MetroAreaCode” means we’re matching on the MetroAreaCode variable from the “x” data frame (CPS), while by.y=“Code” means we’re matching on the Code variable from the “y” data frame (MetroAreaMap). Finally, all.x=TRUE means we want to keep all rows from the “x” data frame (CPS), even if some of the rows’ MetroAreaCode doesn’t match any codes in MetroAreaMap (for those familiar with database terminology, this parameter makes the operation a left outer join instead of an inner join).
Review the new version of the CPS data frame with the summary() and str() functions. What is the name of the variable that was added to the data frame by the merge() operation?
CPS = merge(CPS, MetroAreaMap, by.x="MetroAreaCode", by.y="Code", all.x=TRUE)
How many interviewees have a missing value for the new metropolitan area variable? Note that all of these interviewees would have been removed from the merged data frame if we did not include the all.x=TRUE parameter.
summary(CPS)
MetroAreaCode PeopleInHousehold Region State Age
Min. :10420 Min. : 1.000 Midwest :30684 California :11570 Min. : 0.00
1st Qu.:21780 1st Qu.: 2.000 Northeast:25939 Texas : 7077 1st Qu.:19.00
Median :34740 Median : 3.000 South :41502 New York : 5595 Median :39.00
Mean :35075 Mean : 3.284 West :33177 Florida : 5149 Mean :38.83
3rd Qu.:41860 3rd Qu.: 4.000 Pennsylvania: 3930 3rd Qu.:57.00
Max. :79600 Max. :15.000 Illinois : 3912 Max. :85.00
NA's :34238 (Other) :94069
Married Sex Education
Divorced :11151 Female:67481 High school :30906
Married :55509 Male :63821 Bachelor's degree :19443
Never Married:30772 Some college, no degree:18863
Separated : 2027 No high school diploma :16095
Widowed : 6505 Associate degree : 9913
NA's :25338 (Other) :10744
NA's :25338
Race Hispanic CountryOfBirthCode Citizenship
American Indian : 1433 Min. :0.0000 Min. : 57.00 Citizen, Native :116639
Asian : 6520 1st Qu.:0.0000 1st Qu.: 57.00 Citizen, Naturalized: 7073
Black : 13913 Median :0.0000 Median : 57.00 Non-Citizen : 7590
Multiracial : 2897 Mean :0.1393 Mean : 82.68
Pacific Islander: 618 3rd Qu.:0.0000 3rd Qu.: 57.00
White :105921 Max. :1.0000 Max. :555.00
EmploymentStatus Industry MetroArea.x
Disabled : 5712 Educational and health services :15017 Length:131302
Employed :61733 Trade : 8933 Class :character
Not in Labor Force:15246 Professional and business services: 7519 Mode :character
Retired :18619 Manufacturing : 6791
Unemployed : 4203 Leisure and hospitality : 6364
NA's :25789 (Other) :21618
NA's :65060
MetroArea.y MetroArea
Length:131302 Length:131302
Class :character Class :character
Mode :character Mode :character
Which of the following metropolitan areas has the largest number of interviewees?
table(CPS$MetroArea) %>% sort %>% tail(10)
Houston-Baytown-Sugar Land, TX
1649
Dallas-Fort Worth-Arlington, TX
1863
Minneapolis-St Paul-Bloomington, MN-WI
1942
Boston-Cambridge-Quincy, MA-NH
2229
Providence-Fall River-Warwick, MA-RI
2284
Chicago-Naperville-Joliet, IN-IN-WI
2772
Philadelphia-Camden-Wilmington, PA-NJ-DE
2855
Los Angeles-Long Beach-Santa Ana, CA
4102
Washington-Arlington-Alexandria, DC-VA-MD-WV
4177
New York-Northern New Jersey-Long Island, NY-NJ-PA
5409
Which metropolitan area has the highest proportion of interviewees of Hispanic ethnicity? Hint: Use tapply() with mean, as in the previous subproblem. Calling sort() on the output of tapply() could also be helpful here.
tapply(CPS$Hispanic,CPS$MetroArea,mean) %>% sort %>% tail(5)
El Centro, CA El Paso, TX Brownsville-Harlingen, TX
0.6868687 0.7909836 0.7974684
McAllen-Edinburg-Pharr, TX Laredo, TX
0.9487179 0.9662921
Remembering that CPS$Race == “Asian” returns a TRUE/FALSE vector of whether an interviewee is Asian, determine the number of metropolitan areas in the United States from which at least 20% of interviewees are Asian.
tapply(CPS$Race=="Asian",CPS$MetroArea,mean) %>% sort %>% tail(10)
San Diego-Carlsbad-San Marcos, CA Sacramento-Arden-Arcade-Roseville, CA
0.1422271 0.1424288
Atlantic City, NJ Stockton, CA
0.1441441 0.1554404
Warner Robins, GA Fresno, CA
0.1666667 0.1848185
Vallejo-Fairfield, CA San Jose-Sunnyvale-Santa Clara, CA
0.2030075 0.2417910
San Francisco-Oakland-Fremont, CA Honolulu, HI
0.2467532 0.5019036
Normally, we would look at the sorted proportion of interviewees from each metropolitan area who have not received a high school diploma with the command:
sort(tapply(CPS$Education == "No high school diploma", CPS$MetroArea, mean))
However, none of the interviewees aged 14 and younger have an education value reported, so the mean value is reported as NA for each metropolitan area. To get mean (and related functions, like sum) to ignore missing values, you can pass the parameter na.rm=TRUE. Passing na.rm=TRUE to the tapply function, determine which metropolitan area has the smallest proportion of interviewees who have received no high school diploma.
Just as we did with the metropolitan area information, merge in the country of birth information from the CountryMap data frame, replacing the CPS data frame with the result. If you accidentally overwrite CPS with the wrong values, remember that you can restore it by re-loading the data frame from CPSData.csv and then merging in the metropolitan area information using the command provided in the previous subproblem.
What is the name of the variable added to the CPS data frame by this merge operation?
CPS=merge(CPS,CountryMap,by.x="CountryOfBirthCode",by.y="Code",all.x = TRUE)
How many interviewees have a missing value for the new country of birth variable?
sum(is.na(CPS$Country))
[1] 176
Among all interviewees born outside of North America, which country was the most common place of birth?
table(CPS$Country) %>% sort %>% tail
Puerto Rico China India Philippines Mexico United States
518 581 770 839 3921 115063
What proportion of the interviewees from the “New York-Northern New Jersey-Long Island, NY-NJ-PA” metropolitan area have a country of birth that is not the United States? For this computation, don’t include people from this metropolitan area who have a missing country of birth.
table(CPS$MetroArea == "New York-Northern New Jersey-Long Island, NY-NJ-PA", CPS$Country != "United States")
FALSE TRUE
FALSE 78757 12744
TRUE 3736 1668
Which metropolitan area has the largest number (note – not proportion) of interviewees with a country of birth in India? Hint – remember to include na.rm=TRUE if you are using tapply() to answer this question.
sort(tapply(CPS$Country == "India", CPS$MetroArea, sum, na.rm=TRUE)) %>% tail
San Francisco-Oakland-Fremont, CA
27
Detroit-Warren-Livonia, MI
30
Chicago-Naperville-Joliet, IN-IN-WI
31
Philadelphia-Camden-Wilmington, PA-NJ-DE
32
Washington-Arlington-Alexandria, DC-VA-MD-WV
50
New York-Northern New Jersey-Long Island, NY-NJ-PA
96
In Brazil?
sort(tapply(CPS$Country == "Brazil", CPS$MetroArea, sum, na.rm=TRUE)) %>% tail
Bridgeport-Stamford-Norwalk, CT
7
New York-Northern New Jersey-Long Island, NY-NJ-PA
7
Washington-Arlington-Alexandria, DC-VA-MD-WV
8
Los Angeles-Long Beach-Santa Ana, CA
9
Miami-Fort Lauderdale-Miami Beach, FL
16
Boston-Cambridge-Quincy, MA-NH
18
In Somalia?
sort(tapply(CPS$Country == "Somalia", CPS$MetroArea, sum, na.rm=TRUE)) %>% tail
Columbus, OH Fargo, ND-MN
5 5
Phoenix-Mesa-Scottsdale, AZ Seattle-Tacoma-Bellevue, WA
7 7
St. Cloud, MN Minneapolis-St Paul-Bloomington, MN-WI
7 17