[ACCEPTED]-What does eg %+% do? in R-operators
The ultimate reason is that if you do both 44 general-purpose programming and numerical 43 computations, it is useful to have a large 42 complement of binary operators available. For 41 example, if you store numbers in two-dimensional 40 arrays, you may want to multiply the arrays 39 elementwise, or you may want to compute 38 the matrix product of two arrays. In Matlab 37 these two operators are
*; in R they 36 are
%*%. Python has resisted attempts to add new operators, and 35 so numpy differentiates between the two kinds 34 of product by having two classes: the array 33 class is multiplied elementwise, the matrix 32 class is multiplied in the linear-algebra 31 sense.
Another example from Python is that 30 for lists, plus means concatenation:
[1,2,3]+[4,5] == [1,2,3,4,5]. But 29 for numpy arrays, plus means elementwise 28 addition:
array([1,2]) + array([4,5]) == array([5,7]). If your code needs to do both, you 27 have to convert between classes or use function 26 notation, which can lead to cumbersome-looking 25 code, especially where mathematics is involved.
So 24 it would sometimes be convenient to have 23 more operators available for use, and you 22 might not know in advance what sorts of 21 operators a particular application calls 20 for. Therefore, the implementors of R have 19 chosen to treat as operators anything named 18 like
%foo%, and several examples exist:
%in% is set 17 membership,
%x% is Kronecker product,
%o% is outer 16 product. For an example of a language that 15 has taken this to the extreme, see Fortress (section 14 16 of the specification starts with the 13 rules for operator names).
In the blog post 12 you mentioned, the author is using the ggplot2 graphing 11 package, which defines
%+% to mean some kind 10 of combination of two plot elements. Really 9 it seems to add a method to the bare
+ (which 8 is a generic function so you can define 7 what it means for user-defined objects), but 6 it also defines
%+% so that you can use the 5 ggplot2 meaning of
+ (whatever it is) for 4 other objects. If you install ggplot2, type 3
?`%+%` to see the documentation of that operator, and 2
methods(`+`) to see that a new definition has been added 1 to
There is no generally defined
%+%. Maybe you 6 looked at this question from yesterday where
R> '%+%' <- paste R> "foo" %+% "bar"  "foo bar" R>
and ad-hoc string concatenation 5 function was defined. Generally, the 4 'percent-operator-percent' syntax is open 3 for user-defined functions of two arguments, but 2 there is (AFAIK) no generally accepted version 1 for
%+% that you can expect to be present everywhere.
Based on my quick look at the manual it may be 3 a user defined infix operator, so, it's 2 hard to tell what the actual meaning would 1 be...
I would think binary addition.
More Related questions