s-news
[Top] [All Lists]

Re: Query: Beginer questions on writing functions

To: s-news@lists.biostat.wustl.edu, "Arjun Bhandari" <arb.eu@adia.co.ae>
Subject: Re: Query: Beginer questions on writing functions
From: Tony Plate <tplate@blackmesacapital.com>
Date: Fri, 23 Aug 2002 10:35:50 -0600
In-reply-to: <OFDA5988D4.E683C9F7-ON44256C1D.002D61C4@adiaweb.adia.co.ae >
At 12:57 PM 8/22/2002 +0400, Arjun Bhandari wrote:

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.

As John Fox pointed out, the simplest way to check for missing arguments is the missing() function:

if (missing(x) || missing(y)) stop("Incorrect number of arguments to function")

The reason the expression with ==NULL doesn't work is that x==NULL is not the way to test whether x is equal to NULL. For that, use is.null(x). The expression x==NULL returns a zero-length logical vector (because NULL is a zero-length object).

> length(T==NULL)
[1] 0
> mode(T==NULL)
[1] "logical"
> length(c(T,F)==NULL) # a comparison against a zero-length object always returns a zero-length object
[1] 0
> mode(c(T,F)==NULL)
[1] "logical"

PS. S-plus documentation can be a useful source of information (experiencing frustration is a sign that it's time to read it.) Although it does leave something to be desired in terms of organization, it's pretty easy to find the section that discusses handling missing arguments: Book: "Programmer's Guide to S-plus"; Chapter: 4: Writing functions in S-plus; Section: Specifying argument lists; SubSection: Handling Missing Arguments. (Page 122 in the S-plus 6 edition dated Jul 2001).

hope this helps,

Tony Plate


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