I was wondering how one might go about writing a string concatenation operator in R, something like || in SAS, + in Java/C# or & in Visual Basic.
The easiest way would be to create a special operator using %, like
`%+%` <- function(a, b) paste(a, b, sep="")
but this leads to lots of ugly %
's in the code.
I noticed that +
is defined in the Ops group, and you can write S4 methods for that group, so perhaps something like that would be the way to go. However, I have no experience with S4 language features at all. How would I modify the above function to use S4?
You can also use S3 classes for this:
As others have mentioned, you cannot override the sealed S4 method "+". However, you do not need to define a new class in order to define an addition function for strings; this is not ideal since it forces you to convert the class of strings and thus leading to more ugly code. Instead, one can simply overwrite the "+" function:
Then the following should all work as expected:
This solution feels a bit like a hack, since you are no longer using formal methods but its the only way to get the exact behavior you wanted.
You have given yourself the correct answer -- everything in R is a function, and you cannot define new operators. So
%+%
is as good as it gets.I'll try this (relatively more clean S3 solution)
Code above will change
+
to a generic, and set the+.default
to the original+
, then add new method+.character
to+
If R would thoroghlly comply with S4, the following would have been enough:
But this gives an error that the method is sealed :((. Hopefully this will change in the feature versions of R.
The best you can do is to define new class "string" which would behave exactly as "character" class:
and define the most general method which R allows:
now try: