As for R, when defining a replacement function, should the arguments be named as "x" and "value"?

By "replacement functions" I mean those that are mentioned in this thread. What are the replacement functions in R? , those that look like 'length<-'(x, value) . When I worked with such functions, I came across something strange. It seems that the replacement function only works when the variables are named according to a specific rule.

Here is my code:

 a <- c(1,2,3) 

I will try to change the first element of a using one of the three replacement functions below.

 'first0<-' <- function(x, value){ x[1] <- value x } first0(a) <- 5 a # returns [1] 5 2 3. 

The first one works very well ... but when I change the name of the arguments in the definition,

 'first1<-' <- function(somex, somevalue){ somex[1] <- somevalue somex } first1(a) <- 9 # Error in `first1<-`(`*tmp*`, value = 9) : unused argument (value = 9) a # returns [1] 5 2 3 

It does not work, although the following code is fine:

 a <- 'first1<-'(a, 9) a # returns [1] 9 2 3 

Some other names also work well if they look like x and value , it seems:

 'first2<-' <- function(x11, value11){ x11[1] <- value11 x11 } first2(a) <- 33 a # returns [1] 33 2 3 

That doesn't make sense to me. Do variable names really matter or did I make some mistakes?

+5
source share
1 answer

There are two things here. First, the only real rule for overriding functions is that the new value will be passed as a parameter named value , and this will be the last parameter. Therefore, when you specify the signature function(somex, somevalue) , you get the error message unused argument (value = 9) , and the assignment does not work.

Secondly, everything works with the function(x11, value11) due to partial mapping of parameter names in R. Consider this example

 f<-function(a, value1234=5) { print(value1234) } f(value=5) # [1] 5 

Please note that 5 returned. This behavior is determined by matching arguments in a language definition.

Another way to see what is happening is to print a signature of the call of what is actually called.

 'first0<-' <- function(x, value){ print(sys.call()) x[1] <- value x } a <- c(1,2,3) first0(a) <- 5 # `first0<-`(`*tmp*`, value = 5) 

Thus, the first parameter is actually passed as an unnamed positional parameter, and the new value is passed as the named parameter value= . This is the only parameter name that matters.

+8
source

Source: https://habr.com/ru/post/1201591/


All Articles