s-news
[Top] [All Lists]

Re: Query: Beginer questions on writing functions

To: "Arjun Bhandari" <arb.eu@adia.co.ae>
Subject: Re: Query: Beginer questions on writing functions
From: John Fox <jfox@mcmaster.ca>
Date: Thu, 22 Aug 2002 09:29:57 -0400
Cc: s-news@lists.biostat.wustl.edu
Dear Arjun,

I realized that part of my previous response to your first question was potentially misleading. Checking length(c(...)) won't necessarily give you the number of arguments in ..., for example if some arguments are vectors; length(list(...)) is a better idea.

John



1. How does one check if the correct number of arguments have been input.
     -  I tried to use the following set of statements
        value<-match.call(expand = F)
        if((value$y == NULL) || (value$x == NULL)) stop("Incorrect Number
of arguments to the function")
     - Error: No data to interpret as logical value: e1 || e2
                - I do not quite understand where I am going wrong.

If I follow correctly what you want to do, you can use missing to check whether an argument has been specified; for example,

    > fun <- function(x, y){
    +     if (missing(x) || missing(y)) stop('missing argument')
    +     x + y
    +     }

    > fun(1, 2)
    [1] 3

    > fun(1)
    Problem in fun(1): missing argument
    Use traceback() to see the call stack

On the other hand, if you want your function to take an indefinite number of arguments, you can use the dummy argument ... and check length(c(...)).

-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox@mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------


<Prev in Thread] Current Thread [Next in Thread>