Skip to content
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

Better syntax for mutate() than nested "ifelse" functions #1518

Closed
reedblog opened this issue Nov 7, 2015 · 1 comment
Closed

Better syntax for mutate() than nested "ifelse" functions #1518

reedblog opened this issue Nov 7, 2015 · 1 comment

Comments

@reedblog
Copy link

reedblog commented Nov 7, 2015

All of the dplyr functions make R code more readable except for one pretty common case, conditionally assigning variable values with mutate(). The current syntax is something like:
df <- mutate(df, newvar = ifelse(oldvar %in% c("a", "b", "c"), "group1", ifelse(oldvar %in% c("d", "e", "f"), "group2", ifelse(oldvar %in% c("g", "h", "i"), "group3", NA))))

I saw a question on StackOverflow that gave a much better solution, borrowing from the "mosaic" package: http://stackoverflow.com/questions/24459752/can-dplyr-package-be-used-for-conditional-mutating?rq=1

df <- mutate(df, newvar = derivedFactor(
  "group1" = oldvar %in% c("a", "b", "c"),
  "group2" = oldvar %in% c("d", "e", "f"),
  "group3" = oldvar %in% c("g", "h", "i"),
  .default = NA
))

Could something like this be the default syntax, please?

Data frame for testing: df <- data.frame(oldvar = letters)

@romainfrancois
Copy link
Member

Duplicate of #631

@lock lock bot locked as resolved and limited conversation to collaborators Jun 9, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants