Homework 5

  1. At the top of a new script, include code for importing the nhanes_l.csv data file and for loading ggplot2. Run that code.

    # load packages
    library(ggplot2)
    
    # import data
    nhanes<-read.csv('nhanes_l.csv')
  2. Copy and paste the following code, which will create a categorical variable for age. Run that code.

    nhanes$age4<-(nhanes$ridageyr>=18)+(nhanes$ridageyr>=35)+
      (nhanes$ridageyr>=50)+(nhanes$ridageyr>=65)
    nhanes$age4<-factor(nhanes$age4,1:4,c('18-34','35-49','50-64','65+'))
    Note

    We’ll talk more about this code in Session 7.

  3. Write code for using ggplot2 to create a density plot for systolic blood pressure (bpxosy1), with one density curve for each age group, differentiated by color. Add labels to the axes. Run your code.

    ggplot(nhanes,aes(x=bpxosy1,color=age4))+
       geom_density()+
       labs(x='Systolic blood pressure (mmHg)',y='Density',color='Age')

  4. Add faceting by hypertension (hypertension) and gender (gender), with hypertension defining the rows. For the data argument in ggplot(), you may use subset(nhanes,!is.na(hypertension)) to temporarily remove individuals who are missing a value for hypertension.

    Note

    We’ll talk more about subset() in Session 6.

    ggplot(subset(nhanes,!is.na(hypertension)),aes(x=bpxosy1,color=age4))+
       geom_density()+
       labs(x='Systolic blood pressure (mmHg)',y='Density',color='Age')+
       facet_grid(gender~hypertension)

  5. Write code for creating a violin plot for systolic blood pressure (bpxosy1) versus age group (age4), with systolic blood pressure on the y axis. Add labels to the axes. Add faceting by hypertension (hypertension) and gender (gender), with hypertension defining the rows. For the data argument in ggplot(), you may use subset(nhanes,!is.na(hypertension)) to temporarily remove individuals who are missing a value for hypertension.

    Note

    We’ll talk more about subset() in Session 6.

    ggplot(subset(nhanes,!is.na(hypertension)),aes(y=bpxosy1,x=age4))+
       geom_violin()+
       labs(x='Age (years)',y='Systolic blood pressure (mmHg)')+
       facet_grid(gender~hypertension)