R-beta: Applying functions to vectors--question
Marc Lipsitch
mlipsitch at yahoo.com
Mon Sep 14 04:30:11 CEST 1998
Here is a problem I have encountered with R when calling functions
with vector arguments,
when the vectors contain some values which may be nonsensical as
arguments.
Rather than apply the function piecewise to each element of the
vector, it does something
more complicated (and less helpful).
I have constructed a function f (below) which tests if its argument is
negative; if it is,
it returns 0, if not, it returns sqrt(f).
This works fine with scalar arguments.
If you give it a vector argument, however, it seems to have trouble.
What appears to
happen is that the whole vector is evaluated in the if statement and
in the then part.
If the first value in the vector is a nonsensical argument (negative),
the if is not true, so the function returns a single 0.
If the first value in the vector is a good argument (positive), then
it returns the
sqrt function, applied to each element of the input vector.
So what I'm wondering is -- how can you simply apply the function f to
each element
of the vector without this weird thing happening?
Not having used S, I don't know whether this is
(a) a design feature that is there for a good reason that I just
haven't figured out
(b) a bug in S that has been reproduced in R
or
(c) a bug unique to R.
Can someone help me out? Many thanks in advance
Marc Lipsitch
lipsitch at biology.emory.edu
> f_function(e) {
+
+ out_0
+
+ if(e>0)
+
+ out_sqrt(e)
+
+ out}
>
>
>
> f(-2)
[1] 0
>
> f(-2:2)
[1] 0
>
> f(2:-2)
Warning: NaNs produced in function "sqrt"
[1] 1.414214 1.000000 0.000000 NaN NaN
> f
function (e)
{
out <- 0
if (e > 0)
out <- sqrt(e)
out
}
_________________________________________________________
DO YOU YAHOO!?
Get your free @yahoo.com address at http://mail.yahoo.com
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list