Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Last active October 5, 2017 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainfrancois/eeeed972d6734bcad3ec3dcf872df7ea to your computer and use it in GitHub Desktop.
Save romainfrancois/eeeed972d6734bcad3ec3dcf872df7ea to your computer and use it in GitHub Desktop.
library(rlang)
library(dplyr)
library(purrr)
mutate_when <- function(data, condition, ...){
condition <- enquo(condition)
dots <- exprs(...)
expressions <- map2( dots, syms(names(dots)), ~{
quo( case_when(..condition.. ~ !!.x , TRUE ~ !!.y ) )
})
data %>%
mutate( ..condition.. = !!condition ) %>%
mutate( !!!expressions ) %>%
select( -..condition..)
}
d <- data.frame( x = 1:4, y = 1:4)
mutate_when( d, x < 3,
x = -x,
y = -y
)
@barryrowlingson
Copy link

Error in unname(imap(dots, ~{ : could not find function "imap"

I guess I don't have a modernenoughverse install:

> packageVersion("purrr")
[1] ‘0.2.2’
> packageVersion("dplyr")
[1] ‘0.7.2’
> packageVersion("rlang")
[1] ‘0.1.1’

@romainfrancois
Copy link
Author

I just followed Hadley's suggestion of using map2 and syms ...

@dchiu911
Copy link

dchiu911 commented Oct 5, 2017

purrr::imap first appears in v0.2.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment