Faceting the Wage Dataset

Viewed 85

I am trying to run the code below to give me two histograms side by side comparing the difference in wage between Never Married and Married people. The code does work but I am being told this is the wrong way of getting the answer. I am not sure how to filter the original wage dataset by marital status to include only married and never married without creating a new dataset.

#Create a histogram to summarize the wage column ONLY for Married people
Married <- subset(Wage,Wage$maritl=="2. Married")

#Using facets create two side by side wage histograms for married vs never married people
Never_Married <- subset(Wage,Wage$maritl=="1. Never Married")
hist(Never_Married$wage)

Married_NeverMarried <- full_join(Married,Never_Married)

ggplot(Married_NeverMarried,aes(x=wage))+
  geom_histogram(binwidth=20,color="black",fill="white")+
  facet_grid(.~maritl)

This code below seems to work using the original wage dataset but gives me all of the marriage statuses instead of just 2.

ggplot(Wage,aes(x=wage))+
  geom_histogram()+
  facet_grid(.~ maritl)

Thank you!!

2 Answers

We can use %in% to subset the rows and then plot with the original code in OP's post

library(ISLR)
data(Wage)
library(ggplot2)
library(dplyr)
Wage %>% 
   select(wage, maritl) %>% 
   filter(maritl %in% c("2. Married", "1. Never Married")) %>% 
   ggplot(aes(x = wage)) + 
    geom_histogram(binwidth=20,color="black",fill="white")+
    facet_grid(.~maritl)

-output

enter image description here

One approach is to subset Wage in the call to ggplot:

library(ISLR)
data(Wage)
library(ggplot2)
ggplot(Wage[grepl("1|2",Wage$maritl),] ,aes(x=wage)) +
  geom_histogram() +
  facet_grid(.~ maritl)

enter image description here

Another "tidyverse" option is to use dplyr with filter:

library(dplyr)
Wage %>%
  dplyr::filter(str_detect(maritl,"1|2")) %>%
ggplot(aes(x=wage)) +
  geom_histogram() +
  facet_grid(.~ maritl)

This results in an identical graph.

Related