Skip to content

Instantly share code, notes, and snippets.

@robertzk
Created December 6, 2013 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertzk/7816730 to your computer and use it in GitHub Desktop.
Save robertzk/7816730 to your computer and use it in GitHub Desktop.
R exercise: Create infix versions of set functions: intersect(), union(), setdiff() http://adv-r.had.co.nz/Functions.html
infixed_names <- list(intersect = '', union = 'U', setdiff = '-')
create_infix_operator <- function(name, base_fn, e) {
name <- paste("%", name, "%", sep = '')
assign(name, function(x, y) get(base_fn, envir = e)(x, y), envir = e)
}
lapply(names(infixed_names), function(name) {
create_infix_operator(infixed_names[[name]], name, e = parent.frame(2))
})
# Examples:
cat(" {1, 2, 3) ∩ {2, 3, 4} = {", paste(c(1,2,3) %∩% c(2,3,4), collapse = ', '), "}\n",
"{1, 2, 3) U {2, 3, 4} = {", paste(c(1,2,3) %U% c(2,3,4), collapse = ', '), "}\n",
"{1, 2, 3) - {2, 3, 4} = {", paste(c(1,2,3) %-% c(2,3,4), collapse = ', '), "}\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment