Search code examples
rfunctionself

Call "self" in R function as an argument


I was wondering if there is an elegant way of calling "self" in a R function. An easy example would be the modification of a date, let's say a is a date in a int format (like when you read from excel).

a = 41557
a = as.Date(a, origin = "1899-12-30")

Then "a" is updated with the proper format. Obviously this example is very simple, but in a context of long variable or more complicated procedure one would like to use something like "self". Does something like this exist in R. Self simply meaning take the variable at the left part of the = sign.

a = 41557
a = as.Date(self, origin = "1899-12-30") # what to use for self. 

As a first hint I found out (I think) that some functions are able to call "self" somehow using the "<-" operator for example:

"minc<-" <- function(x, value){x*value}

Gives :

a = 2
a = minc(12)
# a = 24, which is basically : a = self*12

I don't know if such a keyword exist in R, but it would definitely helps in the readability of most of my codes.

As always, thanks for your help !

Romain.


Solution

  • The functionality you're looking for is implemented in the fantastic magrittr package. The version on CRAN introduces a piping operator, %>%, which passes what precedes is as the first argument of what follows it (by default), or replaces a . with the preceding statement.

    More to the point of your question, the version on Github introduces many piping variants, including %<>% which works just like the regular pipe, but includes an overwrite assignment.

    The following statements are equivalent (with magrittr version >= 1.1.0, as available on Github, devtools::install_github("smbache/magrittr")):

    a = as.Date(a, origin = "1899-12-30")
    a = a %>% as.Date(origin = "1899-12-30")
    a %<>% as.Date(., origin = "1899-12-30")
    a %<>% as.Date(origin = "1899-12-30")