Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a string concatenation operator in R

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?

like image 995
Hong Ooi Avatar asked Jan 19 '11 00:01

Hong Ooi


People also ask

How do you concatenate strings in R?

Concatenate two strings # use cbind method to bind the strings into a vector. vec < - cbind(string1, string2) # combined vector. # use paste() function to perform string concatenation. # elements are joined together.

How do I concatenate a string to a column in R?

First, we used the paste() function from base R. Using this function, we combined two and three columns, changed the separator from whitespaces to hyphen (“-”). Second, we used the str_() function to merge columns. Third, we used the unite() function.

Can you use += for string concatenation?

The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .

Which operator is used for string concatenation?

The & operator is recommended for string concatenation because it is defined exclusively for strings and reduces your chances of generating an unintended conversion.


1 Answers

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:

"+" = function(x,y) {     if(is.character(x) || is.character(y)) {         return(paste(x , y, sep=""))     } else {         .Primitive("+")(x,y)     } } 

Then the following should all work as expected:

1 + 4 1:10 + 4  "Help" + "Me" 

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.

like image 106
statsmaths Avatar answered Sep 25 '22 14:09

statsmaths