[Rd] incorrect behaviour of formals (PR#4511)
Luke Tierney
luke at stat.uiowa.edu
Fri Oct 10 15:14:32 MEST 2003
On Fri, 10 Oct 2003 polzehl at wias-berlin.de wrote:
> Full_Name: Jörg Polzehl
> Version: 1.8.0
> OS: Windows XP
> Submission from: (NULL) (62.141.176.1)
>
>
> I encountered a problem when playing with the mle library and specifying
> negative
> starting values for the parameters.
> The reason seems to be an incorrect behaviour of function formals:
>
> glike<-function(a=1,b=1,c=1) a
> > formals(glike)
> $a
> [1] 1
> $b
> [1] 1
> $c
> [1] 1
> > unlist(formals(glike))
> a b c
> 1 1 1
> > glike<-function(a=1,b=1,c= -1) a
> > formals(glike)
> $a
> [1] 1
> $b
> [1] 1
> $c
> -1
> > unlist(formals(glike))
> $a
> [1] 1
> $b
> [1] 1
> $c
> -1
formals is doing what it is supposed to do, returning the formal
argument list of the function specified. The problem is using unlist,
which:
Given a list structure 'x', 'unlist' simplifies it to produce a
vector which contains all the atomic components which occur in
'x'.
If all default argument expressions are atomic components of the same
mode then unlist can simplify. For
> formals(function(x=g(2)) x)
$x
g(2)
> unlist(formals(function(x=g(2)) x))
$x
g(2)
unlist cannot simplify, so it returns the original generic vector.
For your example the first two default argument expressions are
numeric values,
> mode(formals(function(a=1,b=1,c= -1) a)$a)
[1] "numeric"
> mode(formals(function(a=1,b=1,c= -1) a)$b)
[1] "numeric"
but the third is not:
> mode(formals(function(a=1,b=1,c= -1) a)$c)
[1] "call"
> as.list(formals(function(a=1,b=1,c= -1) a)$c)
[[1]]
`-`
[[2]]
[1] 1
The entries in formals are the default argument expressions as
produced by the parser. Positive numbers are parsed to numeric
constants, but the expression -1 is parsed to a call of the unary
minus function applied to the positive value 1.
Bottom line: both formals and unlist are working as documented; code
that uses unlist(formals(...)) ans expects the result to be a numeric
vector needs to be changed.
Best,
luke
--
Luke Tierney
University of Iowa Phone: 319-335-3386
Department of Statistics and Fax: 319-335-3017
Actuarial Science
241 Schaeffer Hall email: luke at stat.uiowa.edu
Iowa City, IA 52242 WWW: http://www.stat.uiowa.edu
More information about the R-devel
mailing list