Skip to content

Instantly share code, notes, and snippets.

@gshotwell
Created October 26, 2019 13:44
Show Gist options
  • Save gshotwell/5b1c84e441e40675581c6d3e75ea0d0b to your computer and use it in GitHub Desktop.
Save gshotwell/5b1c84e441e40675581c6d3e75ea0d0b to your computer and use it in GitHub Desktop.
call <- substitute(ifelse(v == 1,
"banana",
ifelse(v == 2,
2,
NA))
)
parse_ifelse <- function(call) {
if (deparse(call[[3]][[1]]) == "ifelse") {
top_call <- deparse(call[[2]])
return(
paste0(top_call, " & ",
parse_ifelse(call[[3]]))
)
}
top_call <- paste0(deparse(call[[2]]), " ~ ", deparse(call[[3]]))
if (deparse(call[[4]][[1]]) == "ifelse") {
return(c(top_call,
parse_ifelse(call[[4]])))
}
return(paste0(deparse(call[[2]]), " ~ ", deparse(call[[3]])))
}
getTerminalCase <- function(call) {
if (deparse(call[[4]][[1]]) == "ifelse") {
return(getTerminalCase(call[[4]]))
} else {
return(paste0( "TRUE ~ ", deparse(call[[4]])))
}
}
makeCaseWhen <- function(call) {
cases <- c(
parse_ifelse(call),
getTerminalCase(call)
)
out <- c(
"dplyr::case_when(",
paste0(cases, collapse = ",\n"),
")"
)
paste0(out, collapse = "\n")
}
cat(makeCaseWhen(call))
@gshotwell
Copy link
Author

gshotwell commented Oct 26, 2019 via email

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