Reputation: 1977
I'm wondering is there any way to feed more than 2 argument to an operator, or I dont have any choice except using function format! For example I could define merge operator which needs more than 2 Arg.
Here is just an example, I'm not interested in merge functionality:
1.I made an operator to merge two data frames with their common column names A%>>%B
:
`%>>%`<- function(a,b){
by.tmp = intersect(names(a),names(b))
base::merge(a,b,by = by.tmp)
}
2.Now I'm looking for a way to define which column should be matched from data.frame A
to data.frame B
, like:
A %column_name_a>>column_name_b% B
# or feeding 2 arg from each side to operator like follow
# which inside parenthesis return another operator
A (column_name_a %>>% column_name_b) B
# or more advanced
A:column_name_list_a%>>%column_name_list_b:B
I know how to do it with functions, I just want to know is there a way to define more complicated operators to abstract my code.
UPDATE: I managed to right an operator with unknown number of arguments (it is kinda of cascading but it works). here is the approach:
`%>%` <- function(a,b){
ifvalid <- function(a, frame = parent.frame()){
res = try(eval(a,frame),silent = T)
flag = inherits(res, "try-error") | (length(res)==0)
ifelse ((!flag) | (length(a)==1) , return(res), return(
lapply(a, ifvalid,frame=frame)
)
)
}
left_arg = substitute(a)
right_arg= substitute(b)
res = list(
left = ifvalid(left_arg),
right = ifvalid(right_arg)
)
return(res)
}
Example run is:
"X":1:NULL %>% date():`*`
# $left
# $left[[1]]
# .Primitive(":")
#
# $left[[2]]
# $left[[2]][[1]]
# .Primitive(":")
#
# $left[[2]][[2]]
# [1] "X"
#
# $left[[2]][[3]]
# [1] 1
#
#
# $left[[3]]
# list()
#
#
# $right
# $right[[1]]
# .Primitive(":")
#
# $right[[2]]
# [1] "Wed Feb 03 16:04:17 2016"
#
# $right[[3]]
# function (e1, e2) .Primitive("*")
Upvotes: 1
Views: 76
Reputation: 263331
Illustrating the approach outlined above in a comment:
`%>>%`<- function(a,b){
base::merge(a,b[[1]],by = b[[2]])
}
authors %>>% list(books, "name")
#-------
name nationality deceased title other.author
1 McNeil Australia no Interactive Data Analysis <NA>
2 Ripley UK no Spatial Statistics <NA>
3 Ripley UK no Stochastic Simulation <NA>
4 Tierney US no LISP-STAT <NA>
5 Tukey US yes Exploratory Data Analysis <NA>
6 Venables Australia no Modern Applied Statistics ... Ripley
Date used is a slightly simplified version of the code on the ?merge
help page:
authors <- data.frame(
name = I(c("Tukey", "Venables", "Tierney", "Ripley", "McNeil")),
nationality = c("US", "Australia", "US", "UK", "Australia"),
deceased = c("yes", rep("no", 4)))
books <- data.frame(
name = I(c("Tukey", "Venables", "Tierney",
"Ripley", "Ripley", "McNeil", "R Core")),
title = c("Exploratory Data Analysis",
"Modern Applied Statistics ...",
"LISP-STAT",
"Spatial Statistics", "Stochastic Simulation",
"Interactive Data Analysis",
"An Introduction to R"),
other.author = c(NA, "Ripley", NA, NA, NA, NA,
"Venables & Smith"))
Upvotes: 2