[R] Elementary sapply question
Ajay Shah
ajayshah at mayin.org
Mon Jun 21 20:57:30 CEST 2004
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?
Thanks,
-ans.
--
Ajay Shah Consultant
ajayshah at mayin.org Department of Economic Affairs
http://www.mayin.org/ajayshah Ministry of Finance, New Delhi
More information about the R-help
mailing list