# [R] Newbie on functions

Chris Jackson chris.jackson at imperial.ac.uk
Tue Nov 8 17:25:48 CET 2005

```(Ted Harding) wrote:
> 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
>>
>>
>> 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).

In that case the error message would be something like "Argument m is
missing, with no default".

But in this case it looks like the "eval" error message is from within
the deltamethod() function from my CRAN package msm.  Unfortunately, a
limitation of this function is that user-defined variables are not
visible in the first "formula" argument.  I should make the
documentation clearer.

You could work around this as follows.  Build a string from the
values of Q and theta using sprintf(), then convert it into a
formula to pass to deltamethod():

form <- sprintf("~(-2)*sqrt(%f)*cos(%f/3)+x1/3", Q, theta)
stderrb <- deltamethod(as.formula(form), m, cov)

Mail me off list if you want any further help, as this is quite
specialised.

Chris

--
Christopher Jackson <chris.jackson at imperial.ac.uk>, Research Associate,
Department of Epidemiology and Public Health, Imperial College
School of Medicine, Norfolk Place, London W2 1PG

```