[R] Newbie on functions
(Ted Harding)
Ted.Harding at nessie.mcc.ac.uk
Mon Nov 7 21:14:09 CET 2005
On 07-Nov-05 Angelo Secchi wrote:
>
> Hi,
> I'm trying to write a simple function like
>
> case1 <- function (m, cov, Q, R) {
> theta <- (acos(R/sqrt(Q^3)))
> beta <- (-2)*sqrt(Q)*cos(theta/3)+m[1]/3
> rho1 <- (-2)*sqrt(Q)*cos((theta+2*pi)/3)+m[1]/3
> rho2 <- (-2)*sqrt(Q)*cos((theta-2*pi)/3)+m[1]/3
> stderrb <- deltamethod( ~(-2)*sqrt(Q)*cos(theta/3)+x1/3,m,cov)
> stderrr1 <- deltamethod( ~(-2)*sqrt(Q)*cos((theta+2*pi)/3)+x1/3, m,
> cov) stderrr2 <- deltamethod( ~(-2)*sqrt(Q)*cos((theta-2*pi)/3)+x1/3,
> m, cov) stderr <- c(stderrb,stderrr1,stderrr2)
> results <- c(beta,rho1,rho2,stderr)
> results2 <- t(results)
> results2
> }
>
> When I call the function in an IF statement like
>
> if (Q^3>R^2) results2 <- case1() else print('ciccio')
>
> I get
>
> Error in eval(expr, envir, enclos) : Object "theta" not found
>
> I do not understand why, any help?
Because when the function 'case1' is called as "case1()" it
has no information on the values of m, cov, Q and R since
it only looks in its argument list for these values (and
not in the environment from which you called it).
It would be different if, in the function definition, you
had assigned default values for arguments not mentioned in
the function call, since it would then use these values
instead, for example
case1 <- function (m=1, cov=1, Q=1, R=1) {
...
}
but probably you do not want to do anything like that in this case.
Best wishes,
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 07-Nov-05 Time: 20:14:07
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list