Calling "i" in R function as an argument

I was wondering if there is an elegant way to call "i" in the R function. A simple example would be changing a date, let's say a is a date in int format (like when you read excel).

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

      

Then "a" is updated with the appropriate format. Obviously, this example is very simple, but in the context of a long variable or more complex procedure, one would like to use something like "I". Something like this exists in R. Self simply means taking the variable on the left side of the = sign.

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

      

As a first hint, I found (I think) that some functions can call "me" in some way 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 exists in R, but it will definitely help in the readability of most of my codes.

As always, thanks for your help!

Romny.

+3


source to share


2 answers


The functionality you are looking for is implemented in a fantastic package magrittr

. The CRAN version introduces a pipe operator %>%

that passes the previous value as the first argument of what follows (the default) or replaces the .

previous statement.

In addition to the question of your question, the version on Github presents many piping options, including %<>%

one that works exactly like a regular pipe, but includes a rewrite 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")

      

+2


source


Replacement functions can be used like this:

1) as.Date

"as.Date<-" <- function(x, value) as.Date(x, origin = value)

      

Now test it:

a <- 41557
as.Date(a) <- "1899-12-30"
a
## [1] 2013-10-10

      

2) minc



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

      

Now test it:

a <- 2
minc(a) <- 12
a
## [1] 24

      

Note: If you want: you can use self

instead x

:

"as.Date<-" <- function(self, value) as.Date(self, origin = value)
"minc" <- function(self, value) self * value

      

+1


source







All Articles