dplyrExtras icon indicating copy to clipboard operation
dplyrExtras copied to clipboard

code donation: s_recode ( and SQuote )

Open AndreMikulec opened this issue 8 years ago • 2 comments

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"

AndreMikulec avatar Nov 24 '17 03:11 AndreMikulec

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"

skranz avatar Nov 24 '17 23:11 skranz

Looks like a wonderful idea.

AndreMikulec avatar Nov 25 '17 02:11 AndreMikulec