[R] Elementary sapply question
Tony Plate
tplate at blackmesacapital.com
Mon Jun 21 21:14:20 CEST 2004
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:
>
> 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?
All the functions in the apply() family construct the call by just
appending the additional arguments after the first. If you supply argument
names for the additional arguments, those will be supplied to the function
called. This can be used to force different interpretations of
arguments. E.g:
> sapply(3:5, function(x, y) {return(y)}, 1)
[1] 1 1 1
> sapply(3:5, function(x, y) {return(y)}, y=1)
[1] 1 1 1
> sapply(3:5, function(x, y) {return(y)}, x=1)
[1] 3 4 5
> sapply(3:5, function(x, y) {return(y)}, z=1)
Error in FUN(X[[as.integer(1)]], ...) : unused argument(s) (z ...)
>
In the third example, the actual set of arguments in the call to the
anonymous function is something like (3, x=1), so the standard argument
interpretation rules result in the arguments having the values y=3, x=1.
hope this help,
Tony Plate
>Thanks,
>
> -ans.
>
>--
>Ajay Shah Consultant
>ajayshah at mayin.org Department of Economic Affairs
>http://www.mayin.org/ajayshah Ministry of Finance, New Delhi
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
More information about the R-help
mailing list