Tidyverse Practice

Duration: ~30 Minutes

Clock made of Legos

Learning Objectives

  • Manage a project
  • Create a summary dataset
  • Save your script as a record of your data prep

Start your project

  1. Create a new script file.
  2. Add a descriptive header.
  3. Load the tidyverse package.
  4. Load the person-level data.

If you need help, refer to the Tidyverse practice slides.

Summarize your data

In this section, you will create a second dataset that summarizes people based on their survival.

In a workflow, you might write a new script for this section so that each new dataset has its own script file.

Create the survival variable

Create variable SURVIVAL where:

  • "survived" means INJ_SEV does not equal "fatal"
  • "died" means INJ_SEV equals "fatal"

new_fars <- my_fars %>% 
  mutate(SURVIVAL = ifelse(INJ_SEV=="fatal", "died",
                           "survived") )
                           

Group your data

Group the data by your new variable


summary <- new_fars %>% group_by(SURVIVAL)

Summarize your data

Summarize by:

  • total number
  • mean age
  • median age
  • number male and female





summary <- summary %>% 
  summarize(
    total = n(),
    age_mean = mean(AGE, na.rm=TRUE),
    age_median = median(AGE, na.rm=TRUE),
    males = sum(SEX == "male"),
    females = sum(SEX == "female")
  )
  

Link your code

Chain these steps together:

  1. group by SURVIVAL (use new_fars)
  2. summarize by total number, mean and median age, and numbers of males and females
  3. ungroup your variables

fars_summary <- new_fars %>% group_by(SURVIVAL) %>%
  summarize(
    total = n(),
    age_mean = mean(AGE, na.rm=TRUE),
    age_median = median(AGE, na.rm=TRUE),
    males = sum(SEX == "male"),
    females = sum(SEX == "female")
  ) %>% ungroup()
  

View your data

View your summarized dataset.


fars_summary

head(fars_summary)

Save your data

Save your data in the folder data.


write.csv(fars_summary, "data/fars2015nys_Albany_person_bysurvival.csv", 
          row.names = FALSE)
          

And Now You Know!

Q & A

Enjoy R and please fill out our evaluation.