Loading data

library(NHANES)
## Warning: package 'NHANES' was built under R version 4.4.1

Do not include an evaluated install.package() in your Rmd program. What can happen if you do?

Using “install.package()” in my Rmd program can cause installation of the package each time my program is knitted. Instead, I make sure that the package is already installed before coding in the Console.

What is in the “Description” section of the help page for the “NHANES” object?

?NHANES
## starting httpd help server ... done

The “description” section of the help page shows an overview of the dataset. It depicts speciifc details of the dataset, such as where/when/what was gathered. In this specific dataset, a survey by the US National Center for Health Statistics conducted a data collection of health and nutrition surverys from 2009 to 2012.

Viewing the data

What can happen if you have an evaluated View() command in your .Rmd file?

When a “view()” command is in my .Rmd file it will open the data when I knit the doc. Typically, it can cause some issues such as creating a non-interactive environment and rendering issues.

head(NHANES)
##      ID SurveyYr Gender Age AgeDecade AgeMonths Race1 Race3    Education
## 1 51624  2009_10   male  34     30-39       409 White  <NA>  High School
## 2 51624  2009_10   male  34     30-39       409 White  <NA>  High School
## 3 51624  2009_10   male  34     30-39       409 White  <NA>  High School
## 4 51625  2009_10   male   4       0-9        49 Other  <NA>         <NA>
## 5 51630  2009_10 female  49     40-49       596 White  <NA> Some College
## 6 51638  2009_10   male   9       0-9       115 White  <NA>         <NA>
##   MaritalStatus    HHIncome HHIncomeMid Poverty HomeRooms HomeOwn       Work
## 1       Married 25000-34999       30000    1.36         6     Own NotWorking
## 2       Married 25000-34999       30000    1.36         6     Own NotWorking
## 3       Married 25000-34999       30000    1.36         6     Own NotWorking
## 4          <NA> 20000-24999       22500    1.07         9     Own       <NA>
## 5   LivePartner 35000-44999       40000    1.91         5    Rent NotWorking
## 6          <NA> 75000-99999       87500    1.84         6    Rent       <NA>
##   Weight Length HeadCirc Height   BMI BMICatUnder20yrs   BMI_WHO Pulse BPSysAve
## 1   87.4     NA       NA  164.7 32.22             <NA> 30.0_plus    70      113
## 2   87.4     NA       NA  164.7 32.22             <NA> 30.0_plus    70      113
## 3   87.4     NA       NA  164.7 32.22             <NA> 30.0_plus    70      113
## 4   17.0     NA       NA  105.4 15.30             <NA> 12.0_18.5    NA       NA
## 5   86.7     NA       NA  168.4 30.57             <NA> 30.0_plus    86      112
## 6   29.8     NA       NA  133.1 16.82             <NA> 12.0_18.5    82       86
##   BPDiaAve BPSys1 BPDia1 BPSys2 BPDia2 BPSys3 BPDia3 Testosterone DirectChol
## 1       85    114     88    114     88    112     82           NA       1.29
## 2       85    114     88    114     88    112     82           NA       1.29
## 3       85    114     88    114     88    112     82           NA       1.29
## 4       NA     NA     NA     NA     NA     NA     NA           NA         NA
## 5       75    118     82    108     74    116     76           NA       1.16
## 6       47     84     50     84     50     88     44           NA       1.34
##   TotChol UrineVol1 UrineFlow1 UrineVol2 UrineFlow2 Diabetes DiabetesAge
## 1    3.49       352         NA        NA         NA       No          NA
## 2    3.49       352         NA        NA         NA       No          NA
## 3    3.49       352         NA        NA         NA       No          NA
## 4      NA        NA         NA        NA         NA       No          NA
## 5    6.70        77      0.094        NA         NA       No          NA
## 6    4.86       123      1.538        NA         NA       No          NA
##   HealthGen DaysPhysHlthBad DaysMentHlthBad LittleInterest Depressed
## 1      Good               0              15           Most   Several
## 2      Good               0              15           Most   Several
## 3      Good               0              15           Most   Several
## 4      <NA>              NA              NA           <NA>      <NA>
## 5      Good               0              10        Several   Several
## 6      <NA>              NA              NA           <NA>      <NA>
##   nPregnancies nBabies Age1stBaby SleepHrsNight SleepTrouble PhysActive
## 1           NA      NA         NA             4          Yes         No
## 2           NA      NA         NA             4          Yes         No
## 3           NA      NA         NA             4          Yes         No
## 4           NA      NA         NA            NA         <NA>       <NA>
## 5            2       2         27             8          Yes         No
## 6           NA      NA         NA            NA         <NA>       <NA>
##   PhysActiveDays TVHrsDay CompHrsDay TVHrsDayChild CompHrsDayChild
## 1             NA     <NA>       <NA>            NA              NA
## 2             NA     <NA>       <NA>            NA              NA
## 3             NA     <NA>       <NA>            NA              NA
## 4             NA     <NA>       <NA>             4               1
## 5             NA     <NA>       <NA>            NA              NA
## 6             NA     <NA>       <NA>             5               0
##   Alcohol12PlusYr AlcoholDay AlcoholYear SmokeNow Smoke100 Smoke100n SmokeAge
## 1             Yes         NA           0       No      Yes    Smoker       18
## 2             Yes         NA           0       No      Yes    Smoker       18
## 3             Yes         NA           0       No      Yes    Smoker       18
## 4            <NA>         NA          NA     <NA>     <NA>      <NA>       NA
## 5             Yes          2          20      Yes      Yes    Smoker       38
## 6            <NA>         NA          NA     <NA>     <NA>      <NA>       NA
##   Marijuana AgeFirstMarij RegularMarij AgeRegMarij HardDrugs SexEver SexAge
## 1       Yes            17           No          NA       Yes     Yes     16
## 2       Yes            17           No          NA       Yes     Yes     16
## 3       Yes            17           No          NA       Yes     Yes     16
## 4      <NA>            NA         <NA>          NA      <NA>    <NA>     NA
## 5       Yes            18           No          NA       Yes     Yes     12
## 6      <NA>            NA         <NA>          NA      <NA>    <NA>     NA
##   SexNumPartnLife SexNumPartYear SameSex SexOrientation PregnantNow
## 1               8              1      No   Heterosexual        <NA>
## 2               8              1      No   Heterosexual        <NA>
## 3               8              1      No   Heterosexual        <NA>
## 4              NA             NA    <NA>           <NA>        <NA>
## 5              10              1     Yes   Heterosexual        <NA>
## 6              NA             NA    <NA>           <NA>        <NA>

Summarizing the data

summary(NHANES)
##        ID           SurveyYr       Gender          Age          AgeDecade   
##  Min.   :51624   2009_10:5000   female:5020   Min.   : 0.00    40-49 :1398  
##  1st Qu.:56905   2011_12:5000   male  :4980   1st Qu.:17.00    0-9   :1391  
##  Median :62160                                Median :36.00    10-19 :1374  
##  Mean   :61945                                Mean   :36.74    20-29 :1356  
##  3rd Qu.:67039                                3rd Qu.:54.00    30-39 :1338  
##  Max.   :71915                                Max.   :80.00   (Other):2810  
##                                                               NA's   : 333  
##    AgeMonths          Race1           Race3               Education   
##  Min.   :  0.0   Black   :1197   Asian   : 288   8th Grade     : 451  
##  1st Qu.:199.0   Hispanic: 610   Black   : 589   9 - 11th Grade: 888  
##  Median :418.0   Mexican :1015   Hispanic: 350   High School   :1517  
##  Mean   :420.1   White   :6372   Mexican : 480   Some College  :2267  
##  3rd Qu.:624.0   Other   : 806   White   :3135   College Grad  :2098  
##  Max.   :959.0                   Other   : 158   NA's          :2779  
##  NA's   :5038                    NA's    :5000                        
##       MaritalStatus         HHIncome     HHIncomeMid        Poverty     
##  Divorced    : 707   more 99999 :2220   Min.   :  2500   Min.   :0.000  
##  LivePartner : 560   75000-99999:1084   1st Qu.: 30000   1st Qu.:1.240  
##  Married     :3945   25000-34999: 958   Median : 50000   Median :2.700  
##  NeverMarried:1380   35000-44999: 863   Mean   : 57206   Mean   :2.802  
##  Separated   : 183   45000-54999: 784   3rd Qu.: 87500   3rd Qu.:4.710  
##  Widowed     : 456   (Other)    :3280   Max.   :100000   Max.   :5.000  
##  NA's        :2769   NA's       : 811   NA's   :811      NA's   :726    
##    HomeRooms       HomeOwn             Work          Weight      
##  Min.   : 1.000   Own  :6425   Looking   : 311   Min.   :  2.80  
##  1st Qu.: 5.000   Rent :3287   NotWorking:2847   1st Qu.: 56.10  
##  Median : 6.000   Other: 225   Working   :4613   Median : 72.70  
##  Mean   : 6.249   NA's :  63   NA's      :2229   Mean   : 70.98  
##  3rd Qu.: 8.000                                  3rd Qu.: 88.90  
##  Max.   :13.000                                  Max.   :230.70  
##  NA's   :69                                      NA's   :78      
##      Length          HeadCirc         Height           BMI       
##  Min.   : 47.10   Min.   :34.20   Min.   : 83.6   Min.   :12.88  
##  1st Qu.: 75.70   1st Qu.:39.58   1st Qu.:156.8   1st Qu.:21.58  
##  Median : 87.00   Median :41.45   Median :166.0   Median :25.98  
##  Mean   : 85.02   Mean   :41.18   Mean   :161.9   Mean   :26.66  
##  3rd Qu.: 96.10   3rd Qu.:42.92   3rd Qu.:174.5   3rd Qu.:30.89  
##  Max.   :112.20   Max.   :45.40   Max.   :200.4   Max.   :81.25  
##  NA's   :9457     NA's   :9912    NA's   :353     NA's   :366    
##     BMICatUnder20yrs         BMI_WHO         Pulse           BPSysAve    
##  UnderWeight:  55    12.0_18.5   :1277   Min.   : 40.00   Min.   : 76.0  
##  NormWeight : 805    18.5_to_24.9:2911   1st Qu.: 64.00   1st Qu.:106.0  
##  OverWeight : 193    25.0_to_29.9:2664   Median : 72.00   Median :116.0  
##  Obese      : 221    30.0_plus   :2751   Mean   : 73.56   Mean   :118.2  
##  NA's       :8726    NA's        : 397   3rd Qu.: 82.00   3rd Qu.:127.0  
##                                          Max.   :136.00   Max.   :226.0  
##                                          NA's   :1437     NA's   :1449   
##     BPDiaAve          BPSys1          BPDia1           BPSys2     
##  Min.   :  0.00   Min.   : 72.0   Min.   :  0.00   Min.   : 76.0  
##  1st Qu.: 61.00   1st Qu.:106.0   1st Qu.: 62.00   1st Qu.:106.0  
##  Median : 69.00   Median :116.0   Median : 70.00   Median :116.0  
##  Mean   : 67.48   Mean   :119.1   Mean   : 68.28   Mean   :118.5  
##  3rd Qu.: 76.00   3rd Qu.:128.0   3rd Qu.: 76.00   3rd Qu.:128.0  
##  Max.   :116.00   Max.   :232.0   Max.   :118.00   Max.   :226.0  
##  NA's   :1449     NA's   :1763    NA's   :1763     NA's   :1647   
##      BPDia2           BPSys3          BPDia3       Testosterone    
##  Min.   :  0.00   Min.   : 76.0   Min.   :  0.0   Min.   :   0.25  
##  1st Qu.: 60.00   1st Qu.:106.0   1st Qu.: 60.0   1st Qu.:  17.70  
##  Median : 68.00   Median :116.0   Median : 68.0   Median :  43.82  
##  Mean   : 67.66   Mean   :117.9   Mean   : 67.3   Mean   : 197.90  
##  3rd Qu.: 76.00   3rd Qu.:126.0   3rd Qu.: 76.0   3rd Qu.: 362.41  
##  Max.   :118.00   Max.   :226.0   Max.   :116.0   Max.   :1795.60  
##  NA's   :1647     NA's   :1635    NA's   :1635    NA's   :5874     
##    DirectChol       TotChol         UrineVol1       UrineFlow1     
##  Min.   :0.390   Min.   : 1.530   Min.   :  0.0   Min.   : 0.0000  
##  1st Qu.:1.090   1st Qu.: 4.110   1st Qu.: 50.0   1st Qu.: 0.4030  
##  Median :1.290   Median : 4.780   Median : 94.0   Median : 0.6990  
##  Mean   :1.365   Mean   : 4.879   Mean   :118.5   Mean   : 0.9793  
##  3rd Qu.:1.580   3rd Qu.: 5.530   3rd Qu.:164.0   3rd Qu.: 1.2210  
##  Max.   :4.030   Max.   :13.650   Max.   :510.0   Max.   :17.1670  
##  NA's   :1526    NA's   :1526     NA's   :987     NA's   :1603     
##    UrineVol2       UrineFlow2     Diabetes     DiabetesAge        HealthGen   
##  Min.   :  0.0   Min.   : 0.000   No  :9098   Min.   : 1.00   Excellent: 878  
##  1st Qu.: 52.0   1st Qu.: 0.475   Yes : 760   1st Qu.:40.00   Vgood    :2508  
##  Median : 95.0   Median : 0.760   NA's: 142   Median :50.00   Good     :2956  
##  Mean   :119.7   Mean   : 1.149               Mean   :48.42   Fair     :1010  
##  3rd Qu.:171.8   3rd Qu.: 1.513               3rd Qu.:58.00   Poor     : 187  
##  Max.   :409.0   Max.   :13.692               Max.   :80.00   NA's     :2461  
##  NA's   :8522    NA's   :8524                 NA's   :9371                    
##  DaysPhysHlthBad  DaysMentHlthBad  LittleInterest   Depressed   
##  Min.   : 0.000   Min.   : 0.000   None   :5103   None   :5246  
##  1st Qu.: 0.000   1st Qu.: 0.000   Several:1130   Several:1009  
##  Median : 0.000   Median : 0.000   Most   : 434   Most   : 418  
##  Mean   : 3.335   Mean   : 4.127   NA's   :3333   NA's   :3327  
##  3rd Qu.: 3.000   3rd Qu.: 4.000                                
##  Max.   :30.000   Max.   :30.000                                
##  NA's   :2468     NA's   :2466                                  
##   nPregnancies       nBabies         Age1stBaby    SleepHrsNight   
##  Min.   : 1.000   Min.   : 0.000   Min.   :14.00   Min.   : 2.000  
##  1st Qu.: 2.000   1st Qu.: 2.000   1st Qu.:19.00   1st Qu.: 6.000  
##  Median : 3.000   Median : 2.000   Median :22.00   Median : 7.000  
##  Mean   : 3.027   Mean   : 2.457   Mean   :22.65   Mean   : 6.928  
##  3rd Qu.: 4.000   3rd Qu.: 3.000   3rd Qu.:26.00   3rd Qu.: 8.000  
##  Max.   :32.000   Max.   :12.000   Max.   :39.00   Max.   :12.000  
##  NA's   :7396     NA's   :7584     NA's   :8116    NA's   :2245    
##  SleepTrouble PhysActive  PhysActiveDays       TVHrsDay        CompHrsDay  
##  No  :5799    No  :3677   Min.   :1.000   2_hr     :1275   0_to_1_hr:1409  
##  Yes :1973    Yes :4649   1st Qu.:2.000   1_hr     : 884   0_hrs    :1073  
##  NA's:2228    NA's:1674   Median :3.000   3_hr     : 836   1_hr     :1030  
##                           Mean   :3.744   0_to_1_hr: 638   2_hr     : 589  
##                           3rd Qu.:5.000   More_4_hr: 615   3_hr     : 347  
##                           Max.   :7.000   (Other)  : 611   (Other)  : 415  
##                           NA's   :5337    NA's     :5141   NA's     :5137  
##  TVHrsDayChild   CompHrsDayChild Alcohol12PlusYr   AlcoholDay    
##  Min.   :0.000   Min.   :0.000   No  :1368       Min.   : 1.000  
##  1st Qu.:1.000   1st Qu.:0.000   Yes :5212       1st Qu.: 1.000  
##  Median :2.000   Median :1.000   NA's:3420       Median : 2.000  
##  Mean   :1.939   Mean   :2.198                   Mean   : 2.914  
##  3rd Qu.:3.000   3rd Qu.:6.000                   3rd Qu.: 3.000  
##  Max.   :6.000   Max.   :6.000                   Max.   :82.000  
##  NA's   :9347    NA's   :9347                    NA's   :5086    
##   AlcoholYear    SmokeNow    Smoke100         Smoke100n       SmokeAge    
##  Min.   :  0.0   No  :1745   No  :4024   Non-Smoker:4024   Min.   : 6.00  
##  1st Qu.:  3.0   Yes :1466   Yes :3211   Smoker    :3211   1st Qu.:15.00  
##  Median : 24.0   NA's:6789   NA's:2765   NA's      :2765   Median :17.00  
##  Mean   : 75.1                                             Mean   :17.83  
##  3rd Qu.:104.0                                             3rd Qu.:19.00  
##  Max.   :364.0                                             Max.   :72.00  
##  NA's   :4078                                              NA's   :6920   
##  Marijuana   AgeFirstMarij   RegularMarij  AgeRegMarij    HardDrugs  
##  No  :2049   Min.   : 1.00   No  :3575    Min.   : 5.00   No  :4700  
##  Yes :2892   1st Qu.:15.00   Yes :1366    1st Qu.:15.00   Yes :1065  
##  NA's:5059   Median :16.00   NA's:5059    Median :17.00   NA's:4235  
##              Mean   :17.02                Mean   :17.69              
##              3rd Qu.:19.00                3rd Qu.:19.00              
##              Max.   :48.00                Max.   :52.00              
##              NA's   :7109                 NA's   :8634               
##  SexEver         SexAge      SexNumPartnLife   SexNumPartYear   SameSex    
##  No  : 223   Min.   : 9.00   Min.   :   0.00   Min.   : 0.000   No  :5353  
##  Yes :5544   1st Qu.:15.00   1st Qu.:   2.00   1st Qu.: 1.000   Yes : 415  
##  NA's:4233   Median :17.00   Median :   5.00   Median : 1.000   NA's:4232  
##              Mean   :17.43   Mean   :  15.09   Mean   : 1.342              
##              3rd Qu.:19.00   3rd Qu.:  12.00   3rd Qu.: 1.000              
##              Max.   :50.00   Max.   :2000.00   Max.   :69.000              
##              NA's   :4460    NA's   :4275      NA's   :5072                
##       SexOrientation  PregnantNow  
##  Bisexual    : 119   Yes    :  72  
##  Heterosexual:4638   No     :1573  
##  Homosexual  :  85   Unknown:  51  
##  NA's        :5158   NA's   :8304  
##                                    
##                                    
## 

How many missing values are there for weight and height?

There are 78 missing values for weight and 353 missing values for height.

Writing a Function

calculate_mean_difference <- function(df, i, col1, col2) {
    filtered_df <- df[i, ]
     filtered_df <- filtered_df[complete.cases(filtered_df[, c(col1, col2)]), ]
    mean_diff <- mean(filtered_df[[col1]]) - mean(filtered_df[[col2]])
    return(mean_diff)}

Debugging with the Browser Command

Insert the browser() command as the first line inside your function, and pass this new function definition to the R console

calculate_mean_difference <- function(df, i) 
  {browser()
   if (!is.numeric(i)) {
    stop("Indices 'i' must be numeric.")}
   filtered_df <- df[i, ]
  filtered_df <- filtered_df[complete.cases(filtered_df[, c("Weight", "Height")]), ]
  mean_diff <- mean(filtered_df$Weight) - mean(filtered_df$Height)
  
  return(mean_diff)}
indices <- c(1, 2, 3, 5, 7)  # Example numeric indices, adjust as needed
mean_diff <- calculate_mean_difference(NHANES, indices)
## Called from: calculate_mean_difference(NHANES, indices)
## debug at <text>#3: if (!is.numeric(i)) {
##     stop("Indices 'i' must be numeric.")
## }
## debug at <text>#5: filtered_df <- df[i, ]
## debug at <text>#6: filtered_df <- filtered_df[complete.cases(filtered_df[, c("Weight", 
##     "Height")]), ]
## debug at <text>#7: mean_diff <- mean(filtered_df$Weight) - mean(filtered_df$Height)
## debug at <text>#9: return(mean_diff)
print(mean_diff)
## [1] -81.8

Use ls() or the “Environment” tab to see what variables are visible in your new environment within the function. What variables do you see? What are they? How has this changed from before you entered the function?

After looking at the “environment” tab, I saw variables such as ‘df’ and ‘i. These variables changed from ’NHANES’ to ‘df’ and ‘c(“a”, “b”, “c”)’to ’i’.

Write another function

Write another function that takes the same input arguments, but returns the difference in mean weight of males minus mean weight of females.

calculate_gender_weight_difference <- function(df) {
  filtered_df <- df[df$Gender %in% c("male", "female"), ]
  mean_weight_male <- mean(filtered_df$Weight[filtered_df$Gender == "male"], na.rm = TRUE)
  mean_weight_female <- mean(filtered_df$Weight[filtered_df$Gender == "female"], na.rm = TRUE)
  weight_difference <- mean_weight_male - mean_weight_female
  return(weight_difference)
}
print(calculate_gender_weight_difference)
## function(df) {
##   filtered_df <- df[df$Gender %in% c("male", "female"), ]
##   mean_weight_male <- mean(filtered_df$Weight[filtered_df$Gender == "male"], na.rm = TRUE)
##   mean_weight_female <- mean(filtered_df$Weight[filtered_df$Gender == "female"], na.rm = TRUE)
##   weight_difference <- mean_weight_male - mean_weight_female
##   return(weight_difference)
## }
difference <- calculate_gender_weight_difference(NHANES)
print(difference)
## [1] 9.583432