Search code examples
rvariable-assignmentoperator-keyword

What is the effect of including "<-" assignment operator as part of a custom R function name?


Below I define an R function that includes <- as part of its name. I realize, without understanding, that this function uses the value of the right hand side of <-.

Whilst R says that object myfun is not found whilst myfun<- is a function, I cannot understand how I am still able to wrap myx in myfun. In doing so, am I actually calling the myfun<- function? Any insights and guidance from the stackoverflow experts would be appreciated!

'myfun<-' <- function (x,value)   x <- paste0(value, " says hello")
myx <- "my_x"
myy <- "my_y"
myfun(myx) <- myy
myx
[1] "my_y says hello"
myfun
Error: object 'myfun' not found
`myfun<-`
function (x,value)   x <- paste0(value, " says hello")

Solution

  • As @akrun says, a myfun and amyfun<- would be two different functions, the first one for accessing a value from the symbol table, and the other for assigning a value to a symbol. Looking at the "R Language Definition" in the Function Calls" section we see that:

    A special type of function calls can appear on the left hand side of the assignment operator as in

           class(x) <- "foo"
    

    What this construction really does is to call the function class<- with the original object and the right hand side. This function performs the modification of the object and returns the result which is then stored back into the original variable.

    Your definition of the function also has a aspect that exposes a further misconception. The assignment operation inside the body of that function is entirely unnecessary. The value of the <- function is in fact the RHS's value, so unless you had return()-ed the x, the assignment to x would not be needed. Let's leave the assignment out of the function body and try to make the assignment without first creating an entry in the symbol table for myx:

    'myfun<-' <- function (x,value)   paste0(value, " says hello")
    myy <- "my_y"
    myfun(myx) <- myy
    #Error in myfun(myx) <- myy : object 'myx' not found
    

    The usual way of creating an entry in the symbol table for an item is to use one of the empty class constructors:

    myx <- character(0)
    myfun(myx) <- myy
    myx
    #[1] "my_y says hello"   # Success
    

    Note that the assignment operator in the function name directs that the symbol myx be used as the "target", so there is no need for it to have to be a value of "my_x" or anything resembling it's character value. You could have used numeric(0) and you would have only been confusing yourself when you went back later to read your code, but the interpreter would have simply coerced the class of the target symbol to character. R is very weakly typed.