-
Notifications
You must be signed in to change notification settings - Fork 2.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature Request: swap_if(), conditional swapping of values between columns #2149
Comments
Current workaround is the following as suggested by @bpbond
|
@hadley: Is this a particularly common use case we want to support? |
No, I don't think so. However, there is a general pattern that would help resolve this issue: if swap_if <- function(cond, x, y) {
out_x <- if_else(cond, y, x)
out_y <- if_else(!cond, x, y)
setNames(tibble(out_x, out_y), c(expr_name(x), expr_name(y))
}
df %>% mutate(swap_if(V2 == "b", V1, V3)) I don't think the code for getting the names is quite right, but it should be something along those lines. That would also simplify the implementation of |
Returning a tibble is related with #2171. |
But I was confused I think. @hadley: Wouldn't your code work with do()? |
Yes, but |
Groupwise do(), yes. But isn't do() over the entire data frame just a single vectorized function call? The syntax with the dot is a bit awkward, though. |
Oh indeed, it's just that with |
Made a mistake in a partial dataset of a very manual experiment (costly to redo) and realized I needed a conditional swap between two columns.
I envision it looking something like this in practice. I wish I could figure out how to include it in a mutate(), but it requires returning two columns at once.
My attempt at implementation leaves a lot to be desired and is hacked entirely from if_else/replace_with in dplyr.
The text was updated successfully, but these errors were encountered: