add_column()1. Add a new column (year) to the
data
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
Add participation year equal to “2018-19” for all IDs.
d1 %>%
tibble::add_column(year = "2018-19")
# A tibble: 3 x 6
id item1 item2 item3 item4 year
<dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1 10 3 5 3 NA 2018-19
2 11 3 5 1 5 2018-19
3 12 3 1 3 5 2018-19
I can also change the location of the new column by adding the argument .before or .after.
d1 %>%
tibble::add_column(year = "2018-19", .after = "id")
# A tibble: 3 x 6
id year item1 item2 item3 item4
<dbl> <chr> <dbl> <dbl> <dbl> <dbl>
1 10 2018-19 3 5 3 NA
2 11 2018-19 3 5 1 5
3 12 2018-19 3 1 3 5
mutate()1. Add a new column (year) to the
data
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
I can use dplyr::mutate() to create our new variable
“year” and assign it a value that is applied to every row. In this case
I want to assign a value of 1, for the first year of the study. I can
also add the argument .before or .after to change the
location of the new variable.
d1 %>%
dplyr::mutate(year = 1, .after = id)
# A tibble: 3 x 6
id year item1 item2 item3 item4
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 10 1 3 5 3 NA
2 11 1 3 5 1 5
3 12 1 3 1 3 5
Return to Create New Variables