Homework 6

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

  2. In Exercise 3, we used replace() to define missing values for the alcohol-use variable. An alternate way to define missing values is to combine is.na() and object assignment, as shown in the code below.

    nhanes$alcohol_use<-nhanes$alq130
    is.na(nhanes$alcohol_use)<-(nhanes$alcohol_use==777)|(nhanes$alcohol_use==999)

    In the first line, we use object assignment to copy the original alcohol-use variable, alq130, to a new variable, alcohol_use.

    On the right-hand side of the second line, we use a logical object to define the desired missingness. We then use object assignment to redefine missingness. Notice that is.na() is on the left-hand side of the object assignment, and recall that it is a TRUE/FALSE vector indicating whether values are missing. (If you are wondering: the object assignment in this line will preserve any existing missingness in alcohol_use, and add the additional missing values defined by the right-hand side.)

    Copy and paste the above code into your script. Run the code. Verify that the code works as intended.

    table(nhanes$education,useNA='always')
    #|  
    #|               9th-11th grade     College degree or later 
    #|                          666                        2625 
    #|       Earlier than 9th grade High-school graduate or GED 
    #|                          373                        1749 
    #|    Some college or AA degree                        <NA> 
    #|                         2370                         370
    table(nhanes$dmdeduc2,useNA='always')
    #|  
    #|     1    2    3    4    5    9 <NA> 
    #|   373  666 1749 2370 2625   11  359
  3. Use sum() and is.na() to find the number of people who are missing a value for hypertension. Verify that this matches the number of people who are missing bpxosy1 or missing bpxodi1.

    sum(is.na(nhanes$hypertension))
    #|  [1] 2030
    sum(is.na(nhanes$bpxosy1)|is.na(nhanes$bpxodi1))
    #|  [1] 2030
  4. Use sum(), is.na(), and negation to find the number of people who are not missing a value of hypertension.

    sum(!is.na(nhanes$hypertension))
    #|  [1] 6123
  5. Use sum() and !is.na() to find the number of people who are not missing bpxodi1 and not missing bpxodi2.

    sum(!is.na(nhanes$bpxosy1)&!is.na(nhanes$bpxodi1))
    #|  [1] 6123
  6. Make a violin plot of systolic blood pressure (bpxosy1) versus hypertension status (hypertension), but subset the data to individuals who are 60 years of age (ridageyr) or older and omit people who have a missing value of hypertension.

    ggplot(subset(nhanes,ridageyr>=60&!is.na(hypertension)),
           aes(x=bpxodi1,y=bpxosy1,color=hypertension))+
       geom_point()+
       labs(x='Diastolic blood pressure (mmHg)',
            y='Systolic blood pressure (mmHg)',
            color='Hypertension')