This function changes the value of a data frame's column, then binds back to itself in order to fit into a pipeline. This preserves grouping, and if group
is a factor, returns group
as a factor with expanded levels.
bind_self(.data, group, new_value, append = FALSE, .id = NULL)
A data frame.
Bare column name of the column needing to be changed.
String giving the new value for column group
.
Logical: should new values be appended to the end of data
, or prepended to the beginning (the default)?
Optional, inheriting from [dplyr::bind_rows()]
: if a string, will create IDs for each data frame and create a column of IDs with the name given as .id
.
A data frame with twice as many rows as the original.
town_populations <- data.frame(
name = c("East Haven", "Hamden", "West Haven"),
pop = c(29015, 61476, 54972)
)
town_populations %>%
dplyr::mutate(measure = "total_pop") %>%
bind_self(group = name, new_value = "Inner Ring towns")
#> name pop measure
#> 1 Inner Ring towns 29015 total_pop
#> 2 Inner Ring towns 61476 total_pop
#> 3 Inner Ring towns 54972 total_pop
#> 4 East Haven 29015 total_pop
#> 5 Hamden 61476 total_pop
#> 6 West Haven 54972 total_pop
town_populations %>%
dplyr::group_by(name) %>%
bind_self(group = name, new_value = "Inner Ring towns") %>%
dplyr::summarise(pop = sum(pop))
#> # A tibble: 4 × 2
#> name pop
#> <chr> <dbl>
#> 1 East Haven 29015
#> 2 Hamden 61476
#> 3 Inner Ring towns 145463
#> 4 West Haven 54972