How to write generic function with two inputs?How to sort a dataframe by multiple column(s)How to join (merge) data frames (inner, outer, left, right)Grouping functions (tapply, by, aggregate) and the *apply familyHow to make a great R reproducible exampleArguments and classes for writing (generic) functions in RWriting generic function for tables that works when the input happens to be vectorHow to retrieve formals of a primitive function?Error within function using solve() in RSubsetting data as generic function in RWriting if / ifelse function in R

How to prevent "they're falling in love" trope

Can I run a new neutral wire to repair a broken circuit?

Why do bosons tend to occupy the same state?

Can compressed videos be decoded back to their uncompresed original format?

Is it logically or scientifically possible to artificially send energy to the body?

Do UK voters know if their MP will be the Speaker of the House?

Detention in 1997

ssTTsSTtRrriinInnnnNNNIiinngg

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

How to tell a function to use the default argument values?

iPad being using in wall mount battery swollen

Personal Teleportation: From Rags to Riches

Is it acceptable for a professor to tell male students to not think that they are smarter than female students?

Why would the Red Woman birth a shadow if she worshipped the Lord of the Light?

How do I gain back my faith in my PhD degree?

Why doesn't using multiple commands with a || or && conditional work?

Cursor Replacement for Newbies

What mechanic is there to disable a threat instead of killing it?

In 'Revenger,' what does 'cove' come from?

Examples of smooth manifolds admitting inbetween one and a continuum of complex structures

Why can't we play rap on piano?

GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?

What is the idiomatic way to say "clothing fits"?

How could indestructible materials be used in power generation?



How to write generic function with two inputs?


How to sort a dataframe by multiple column(s)How to join (merge) data frames (inner, outer, left, right)Grouping functions (tapply, by, aggregate) and the *apply familyHow to make a great R reproducible exampleArguments and classes for writing (generic) functions in RWriting generic function for tables that works when the input happens to be vectorHow to retrieve formals of a primitive function?Error within function using solve() in RSubsetting data as generic function in RWriting if / ifelse function in R













9















I am a newbee in programming, and I run into an issue with R about generic function: how to write it when there are multiple inputs?



For an easy example, for dataset and function



z <- c(2,3,4,5,8)
calc.simp <- function(a,x)a*x+8
# Test the function:
calc.simp(x=z,a=3)
[1] 14 17 20 23 32


Now I change the class of z:
class(z) <- 'simp'
How should I write the generic function 'calc' as there are two inputs?
My attempts and errors are below:



calc <- function(x) UseMethod('calc',x)
calc(x=z)
Error in calc.simp(x = z) : argument "a" is missing, with no default


And



calc <- function(x,y) UseMethod('calc',x,y)
Error in UseMethod("calc", x, y) : unused argument (y)


My confusion might be a fundamental one as I am just a beginner. Please help! Thank you very much!










share|improve this question







New contributor




Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    What do you expect to be returned from calc(x=z)? You aren't giving your function a value for a and your function depends on it. Also you can let your generic function know there may be other argumets with calc <- function(x, ...) UseMethod('calc',x)

    – MrFlick
    5 hours ago












  • What do you want your function to do? Your first function (calc.simp) still works even after changing the class of z.

    – Luis
    4 hours ago











  • @MrFlick I simply want to test whether my generic function can work! It helps me understand the dispatch mechanism better. The 'function(x,...)' works perfectly for my question. Thank you so much! :)

    – Branda Newbee
    4 hours ago












  • question is about dispatching? didn't see this keyword anywhere on this page, hence adding it here.

    – chinsoon12
    22 mins ago















9















I am a newbee in programming, and I run into an issue with R about generic function: how to write it when there are multiple inputs?



For an easy example, for dataset and function



z <- c(2,3,4,5,8)
calc.simp <- function(a,x)a*x+8
# Test the function:
calc.simp(x=z,a=3)
[1] 14 17 20 23 32


Now I change the class of z:
class(z) <- 'simp'
How should I write the generic function 'calc' as there are two inputs?
My attempts and errors are below:



calc <- function(x) UseMethod('calc',x)
calc(x=z)
Error in calc.simp(x = z) : argument "a" is missing, with no default


And



calc <- function(x,y) UseMethod('calc',x,y)
Error in UseMethod("calc", x, y) : unused argument (y)


My confusion might be a fundamental one as I am just a beginner. Please help! Thank you very much!










share|improve this question







New contributor




Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    What do you expect to be returned from calc(x=z)? You aren't giving your function a value for a and your function depends on it. Also you can let your generic function know there may be other argumets with calc <- function(x, ...) UseMethod('calc',x)

    – MrFlick
    5 hours ago












  • What do you want your function to do? Your first function (calc.simp) still works even after changing the class of z.

    – Luis
    4 hours ago











  • @MrFlick I simply want to test whether my generic function can work! It helps me understand the dispatch mechanism better. The 'function(x,...)' works perfectly for my question. Thank you so much! :)

    – Branda Newbee
    4 hours ago












  • question is about dispatching? didn't see this keyword anywhere on this page, hence adding it here.

    – chinsoon12
    22 mins ago













9












9








9


1






I am a newbee in programming, and I run into an issue with R about generic function: how to write it when there are multiple inputs?



For an easy example, for dataset and function



z <- c(2,3,4,5,8)
calc.simp <- function(a,x)a*x+8
# Test the function:
calc.simp(x=z,a=3)
[1] 14 17 20 23 32


Now I change the class of z:
class(z) <- 'simp'
How should I write the generic function 'calc' as there are two inputs?
My attempts and errors are below:



calc <- function(x) UseMethod('calc',x)
calc(x=z)
Error in calc.simp(x = z) : argument "a" is missing, with no default


And



calc <- function(x,y) UseMethod('calc',x,y)
Error in UseMethod("calc", x, y) : unused argument (y)


My confusion might be a fundamental one as I am just a beginner. Please help! Thank you very much!










share|improve this question







New contributor




Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I am a newbee in programming, and I run into an issue with R about generic function: how to write it when there are multiple inputs?



For an easy example, for dataset and function



z <- c(2,3,4,5,8)
calc.simp <- function(a,x)a*x+8
# Test the function:
calc.simp(x=z,a=3)
[1] 14 17 20 23 32


Now I change the class of z:
class(z) <- 'simp'
How should I write the generic function 'calc' as there are two inputs?
My attempts and errors are below:



calc <- function(x) UseMethod('calc',x)
calc(x=z)
Error in calc.simp(x = z) : argument "a" is missing, with no default


And



calc <- function(x,y) UseMethod('calc',x,y)
Error in UseMethod("calc", x, y) : unused argument (y)


My confusion might be a fundamental one as I am just a beginner. Please help! Thank you very much!







r generic-programming






share|improve this question







New contributor




Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 5 hours ago









Branda NewbeeBranda Newbee

483




483




New contributor




Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Branda Newbee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1





    What do you expect to be returned from calc(x=z)? You aren't giving your function a value for a and your function depends on it. Also you can let your generic function know there may be other argumets with calc <- function(x, ...) UseMethod('calc',x)

    – MrFlick
    5 hours ago












  • What do you want your function to do? Your first function (calc.simp) still works even after changing the class of z.

    – Luis
    4 hours ago











  • @MrFlick I simply want to test whether my generic function can work! It helps me understand the dispatch mechanism better. The 'function(x,...)' works perfectly for my question. Thank you so much! :)

    – Branda Newbee
    4 hours ago












  • question is about dispatching? didn't see this keyword anywhere on this page, hence adding it here.

    – chinsoon12
    22 mins ago












  • 1





    What do you expect to be returned from calc(x=z)? You aren't giving your function a value for a and your function depends on it. Also you can let your generic function know there may be other argumets with calc <- function(x, ...) UseMethod('calc',x)

    – MrFlick
    5 hours ago












  • What do you want your function to do? Your first function (calc.simp) still works even after changing the class of z.

    – Luis
    4 hours ago











  • @MrFlick I simply want to test whether my generic function can work! It helps me understand the dispatch mechanism better. The 'function(x,...)' works perfectly for my question. Thank you so much! :)

    – Branda Newbee
    4 hours ago












  • question is about dispatching? didn't see this keyword anywhere on this page, hence adding it here.

    – chinsoon12
    22 mins ago







1




1





What do you expect to be returned from calc(x=z)? You aren't giving your function a value for a and your function depends on it. Also you can let your generic function know there may be other argumets with calc <- function(x, ...) UseMethod('calc',x)

– MrFlick
5 hours ago






What do you expect to be returned from calc(x=z)? You aren't giving your function a value for a and your function depends on it. Also you can let your generic function know there may be other argumets with calc <- function(x, ...) UseMethod('calc',x)

– MrFlick
5 hours ago














What do you want your function to do? Your first function (calc.simp) still works even after changing the class of z.

– Luis
4 hours ago





What do you want your function to do? Your first function (calc.simp) still works even after changing the class of z.

– Luis
4 hours ago













@MrFlick I simply want to test whether my generic function can work! It helps me understand the dispatch mechanism better. The 'function(x,...)' works perfectly for my question. Thank you so much! :)

– Branda Newbee
4 hours ago






@MrFlick I simply want to test whether my generic function can work! It helps me understand the dispatch mechanism better. The 'function(x,...)' works perfectly for my question. Thank you so much! :)

– Branda Newbee
4 hours ago














question is about dispatching? didn't see this keyword anywhere on this page, hence adding it here.

– chinsoon12
22 mins ago





question is about dispatching? didn't see this keyword anywhere on this page, hence adding it here.

– chinsoon12
22 mins ago












1 Answer
1






active

oldest

votes


















8














I'd suggest you model your generic function off of the template used by innumerable base R functions as, e.g., mean:



> mean
function (x, ...)
UseMethod("mean")


In your case, that would translate to the following generic which (if I understand your question correctly) works just fine:



calc <- function(x, ...) UseMethod('calc')

calc.simp <- function(a, x)
x <- unclass(x)
a * x + 8



## Try it out

z <- c(2,3,4,5,8)
class(z) <- "simp"

calc.simp(x = z, 10)
## [1] 28 38 48 58 88

calc(x = z, 10)
## [1] 28 38 48 58 88





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    Branda Newbee is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55503025%2fhow-to-write-generic-function-with-two-inputs%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    8














    I'd suggest you model your generic function off of the template used by innumerable base R functions as, e.g., mean:



    > mean
    function (x, ...)
    UseMethod("mean")


    In your case, that would translate to the following generic which (if I understand your question correctly) works just fine:



    calc <- function(x, ...) UseMethod('calc')

    calc.simp <- function(a, x)
    x <- unclass(x)
    a * x + 8



    ## Try it out

    z <- c(2,3,4,5,8)
    class(z) <- "simp"

    calc.simp(x = z, 10)
    ## [1] 28 38 48 58 88

    calc(x = z, 10)
    ## [1] 28 38 48 58 88





    share|improve this answer





























      8














      I'd suggest you model your generic function off of the template used by innumerable base R functions as, e.g., mean:



      > mean
      function (x, ...)
      UseMethod("mean")


      In your case, that would translate to the following generic which (if I understand your question correctly) works just fine:



      calc <- function(x, ...) UseMethod('calc')

      calc.simp <- function(a, x)
      x <- unclass(x)
      a * x + 8



      ## Try it out

      z <- c(2,3,4,5,8)
      class(z) <- "simp"

      calc.simp(x = z, 10)
      ## [1] 28 38 48 58 88

      calc(x = z, 10)
      ## [1] 28 38 48 58 88





      share|improve this answer



























        8












        8








        8







        I'd suggest you model your generic function off of the template used by innumerable base R functions as, e.g., mean:



        > mean
        function (x, ...)
        UseMethod("mean")


        In your case, that would translate to the following generic which (if I understand your question correctly) works just fine:



        calc <- function(x, ...) UseMethod('calc')

        calc.simp <- function(a, x)
        x <- unclass(x)
        a * x + 8



        ## Try it out

        z <- c(2,3,4,5,8)
        class(z) <- "simp"

        calc.simp(x = z, 10)
        ## [1] 28 38 48 58 88

        calc(x = z, 10)
        ## [1] 28 38 48 58 88





        share|improve this answer















        I'd suggest you model your generic function off of the template used by innumerable base R functions as, e.g., mean:



        > mean
        function (x, ...)
        UseMethod("mean")


        In your case, that would translate to the following generic which (if I understand your question correctly) works just fine:



        calc <- function(x, ...) UseMethod('calc')

        calc.simp <- function(a, x)
        x <- unclass(x)
        a * x + 8



        ## Try it out

        z <- c(2,3,4,5,8)
        class(z) <- "simp"

        calc.simp(x = z, 10)
        ## [1] 28 38 48 58 88

        calc(x = z, 10)
        ## [1] 28 38 48 58 88






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 4 hours ago

























        answered 4 hours ago









        Josh O'BrienJosh O'Brien

        130k18280390




        130k18280390






















            Branda Newbee is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Branda Newbee is a new contributor. Be nice, and check out our Code of Conduct.












            Branda Newbee is a new contributor. Be nice, and check out our Code of Conduct.











            Branda Newbee is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55503025%2fhow-to-write-generic-function-with-two-inputs%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Magento 2 duplicate PHPSESSID cookie when using session_start() in custom php scriptMagento 2: User cant logged in into to account page, no error showing!Magento duplicate on subdomainGrabbing storeview from cookie (after using language selector)How do I run php custom script on magento2Magento 2: Include PHP script in headerSession lock after using Cm_RedisSessionscript php to update stockMagento set cookie popupMagento 2 session id cookie - where to find it?How to import Configurable product from csv with custom attributes using php scriptMagento 2 run custom PHP script

            Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

            How to solve knockout JS error in Magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2