[R] passing a modified argument to an S3 method

Jeff Newmiller jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Sat Apr 20 18:34:27 CEST 2024


The parameters in a specific call to a function are stored in a special list which is used to move/copy data from the calling environment into the environment created for a particular function call.

UseMethod does not act like a normal function call... it does a kind of magic substitution of the implementation method `test.default` into the call stack where the generic function `test` was. The argument list remains, but the environment associated with the generic function `test` is discarded in the process. The argument list was never actually modified in `test`... just the environment.

You are expected to think of `test` as a placeholder... a kind of abstract method that doesn't actually do anything other than map from a generic method to an implementation method. Your goal of adding shared behavior this way is not possible.

I recommend reading Advanced R in book form or online to help you navigate R behavior like this.

On April 20, 2024 8:51:23 AM PDT, Bert Gunter <bgunter.4567 using gmail.com> wrote:
>I do not understand what your goal is here (more context may be helpful,
>perhaps to others rather than me). So I doubt this is what you want, but
>here is a guess -- no need to respond if it is unhelpful:
>
>## test.default returns NULL if object "y" not found in **calling
>environment and enclosures**;
>## otherwise y.
>
>test <- function(x){
>   UseMethod("test")
>}
>test.default <- function(x){
>   tryCatch(y, error = function(e)NULL)
>}
>
>## y not found
>test(x=3)
>NULL
>
>## y found
>> y <- 'abcd'
>> test(x = 3)
>[1] "abcd"
>
>Cheers,
>Bert
>
>
>
>
>On Sat, Apr 20, 2024 at 4:23 AM CRAN.r via R-help <r-help using r-project.org>
>wrote:
>
>> Is there a way to pass a modified argument from an S3 generic to a
>> method?  Here's a non-working example that I want to return "abcd".
>>
>>   test <- function(x, y = NULL){
>>     y <- "abcd"
>>     UseMethod("test")
>>   }
>>   test.default <- function(x, y = NULL) y
>>   test(x = 3)
>>
>> Is that possible? I've looked around a lot, but can't find any examples or
>> discussion.
>>
>> Jay
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

-- 
Sent from my phone. Please excuse my brevity.



More information about the R-help mailing list