Skip to content

Instantly share code, notes, and snippets.

@MyKo101
Last active October 29, 2020 00:18
Show Gist options
  • Save MyKo101/072e609bbb3b186d4c55f56d0a0aafd5 to your computer and use it in GitHub Desktop.
Save MyKo101/072e609bbb3b186d4c55f56d0a0aafd5 to your computer and use it in GitHub Desktop.
Allows for the manipulation of a subset of a data.frame based on a predicate. Similar to using `if_else()` inside `mutate()`, but also allows for the use of `across()` style mutations
mutate_where <- function(x,predicate,...){
full_x <- mutate(x,..row_ids = 1:n())
.predicate <- enquo(predicate)
predicated_x <- filter(full_x,!!.predicate)
other_x <- filter(full_x,!(!!.predicate)|is.na(!!.predicate))
mutated_x <- mutate(predicated_x,!!!enquos(...))
return_x_unsorted <- bind_rows(mutated_x,other_x)
return_x_sorted <- arrange(return_x_unsorted,..row_ids)
select(return_x_sorted,-..row_ids)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment