[R] Elementary sapply question

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Jun 21 21:08:36 CEST 2004


You really ought to name ... arguments. sapply(x, f, y=3) makes it clear 
that f(xx, y=3) is called.  But `optional arguments' necessarily come 
after compulsory  ones, which resolves the ambiguity you see.

Please note that

1) functions return their values
2) a function body is an expression, so { } is only needed to group 
expressions.  And the same for for() loops.

Andy's f is *much* easier to read than your pythagorean.

3) It is very hard to parse code in which both <- and = are used for 
assignment. Please use <- to avoid hard to read code.


On Tue, 22 Jun 2004, Ajay Shah wrote:

> I had asked:
>   > > My problem is this. Suppose I have:
>   > >      pythagorean <- function(x, y) {
>   > >        return(x*x + y*y)
>   > >      }
>   > > 
>   > > then how do I utilise sapply to replace
>   > >      fixed.x = 3
>   > >      y.values = c(3,4,5)
>   > >      answers=numeric(3)
>   > >      for (i in 1:3) {
>   > >          answers[i] = pythagorean(fixed.x, y.values[i])
>   > >      }
> 
> On Mon, Jun 21, 2004 at 02:49:48PM -0400, Liaw, Andy wrote:
> > At least two ways:
> > 
> > 1. Use extra argument in the function being sapply()'ed; e.g.,
> > 
> > > f <- function(x, y) x*x + y*y
> > > x <- 3:5
> > > sapply(x, f, 3)
> > [1] 18 25 34
> > 
> > [See the "..." argument in ?sapply.]
> 
> I am aware of the "..." in sapply(). I am unable to understand how
> sapply will know where to utilise the x[i] values: as the 1st arg or
> the 2nd arg for f(x, y)?
> 
> That is, when I say:
> 
>      sapply(x, f, 3)
> 
> how does sapply know that I mean:
> 
>     for (i in 3:5) {
>         f(i, 3)
>     }
> 
> and not
> 
>     for (i in 3:5) {
>         f(3, i)
>     }
> 
> How would we force sapply to use one or the other interpretation?

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list