Package: dplyr


Function: mutate()


1. Create a new scored variable for item1

Review the data (d1)

# A tibble: 3 x 5
     id item1 item2 item3 item4
  <dbl> <dbl> <dbl> <dbl> <dbl>
1    10     3     5     3    NA
2    11     3     5     1     5
3    12     3     1     3     5

item1 through item4 were all multiple choice variables with one correct answer. We now want to score these variables to be correct (1) or incorrect (0).

Item1: correct answer = 3
Item2: correct answer = 5
Item3: correct answer = 3
Item4: correct answer = 5

  • Note: Here we use dplyr::mutate() to create a new variable, named item1_scored. We could have also chosen to name it item1 and write over the original variable.

  • Note: As we learned from the Recode section, we can recode this variable in many ways including dplyr::recode(), dplyr::if_else() or dplyr::case_when(). In this case we use dplyr::case_when().

d1 %>%
  dplyr::mutate(item1_scored = 
                  dplyr::case_when(
                    item1 == 3 ~ 1,
                    TRUE ~ 0))
# A tibble: 3 x 6
     id item1 item2 item3 item4 item1_scored
  <dbl> <dbl> <dbl> <dbl> <dbl>        <dbl>
1    10     3     5     3    NA            1
2    11     3     5     1     5            1
3    12     3     1     3     5            1

Return to Create New Variables