dplyrExtras
dplyrExtras copied to clipboard
code donation: s_recode ( and SQuote )
s_recode <- function(.x, ..., .default = NULL, .missing = NULL) {
eval.string.PAT.named_dots.default.missing(.x, "recode", .default, .missing, ...)
}
eval.string.PAT.named_dots.default.missing <- function(.x, .fun.name, .default, .missing, ...) {
args = list(...)
args = unlist(args)
args = paste0(names(args), " = ", args)
DEFAULT = if(!is.null(.default)) { paste0(", .default = ", .default) } else { "" }
MISSING = if(!is.null(.missing)) { paste0(", .missing = ", .missing) } else { "" }
code = paste0(.fun.name,"(.x, ", paste0(args, collapse=", "), DEFAULT, MISSING, ")" )
v = eval(parse(text=code,srcfile=NULL))
v
}
SQuote <- function(x) { sapply( x , function(xx) { paste0("'", xx, "'") }, USE.NAMES = FALSE ) }
# > SQuote(letters[1:3])
# [1] "'a'" "'b'" "'c'"
new_letters <- SQuote(c("alpha", "beta"))
names(new_letters) <- c("a","b")
# > new_letters
# a b
# "'alpha'" "'beta'"
# > s_recode(letters[1:3], new_letters)
# [1] "alpha" "beta" "c"
# > s_recode(letters[1:3], new_letters, .default = "'gamma'")
# [1] "alpha" "beta" "gamma"
I wonder, whether we might get the same functionality with a simple do.call and the existing recode function:
> new.letters=c("a"= "alpha", b= "beta")
> do.call(recode, c(list(letters[1:3]), as.list(new.letters)))
[1] "alpha" "beta" "c"
> do.call(recode, c(list(letters[1:3]), as.list(new.letters), list(.default="gamma")))
[1] "alpha" "beta" "gamma"
Looks like a wonderful idea.