If you have something like
lapply(x, f, ...)
What lapply() does (which is the same as what sapply() does, except sapply()
tries to `simplify' the result) is roughly:
result <- vector(mode="list", length=length(x))
for (i in seq(along(x)) {
result[[i]] <- f(x[i], ...)
}
I.e., it takes the fi
At Monday 12:57 PM 6/21/2004, Ajay Shah wrote:
[...snip...]
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:
guess that because these are 2 examples, it is no surprise that the
> results are different. Why is this? If ?mapply is giving me a clue, I'm not
> seeing it.
>
> Thanks,
> -Brian.
>
>
> -Original Message-
> From: [EMAIL PROTECTED]
> [mailto:[EMAIL PROTECTED
as the second example you were more explicit about the
arguments order.
--sundar
-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Liaw, Andy
Sent: Monday, June 21, 2004 11:50 AM
To: 'Ajay Shah'; r-help
Subject: RE: [R] Elementary sapply quest
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
-help
Subject: RE: [R] Elementary sapply question
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.]
2. More generally, if both x a
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
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.]
2. More generally, if both x and y are vectors (of the same length), then
you can use mapply(); e.g.,
I am discovering sapply! :-) Could you please help me with a very
elementary question?
Here is what I know. The following two programs generate the same answer.
+
Loops version| sapply version