gl() in S -- puzzle

Martin Maechler Martin Maechler <maechler@stat.math.ethz.ch>
Tue, 30 Jun 1998 10:45:38 +0200


In order to run some  R examples in  S & Splus,
I want the gl() function in S.

In R, it is

gl <- function (n, k, length = n * k, labels = 1:n, ordered = FALSE) 
	factor(rep(rep(1:n, rep(k, n)), length = length), labels = labels, 
	      ordered = ordered)

Since S's  factor() has no "ordered= F" argument,
in S we need to call ordered() instead of factor() in the case of
ordered=T.

I came up with the following definition

gl <- function (n, k, length = n * k, labels = 1:n, ordered = FALSE) 
  (if(ordered) get("ordered",mode="function") else factor)(
                               rep(rep(1:n, rep(k, n)), length = length),
                               labels = labels)

which works both in R and S,
as long as you keep ordered = FALSE), e.g.

	gl(3,2,12)
	gl(2,8,32, label=c("Ctnrl","Treat"))

Then, in R (with the above definition of gl() [and with the builtin one]):

    R> gl(3,4,24, ordered=T)
     [1] 1 1 1 1 2 2 2 2 3 3 3 3 1 1 1 1 2 2 2 2 3 3 3 3
    Levels:  1 < 2 < 3 

However, in S

	S> gl(3,4,24, ordered=T)

	Error in gl: object of mode ( and length 2 used as string value: (if(ordered) get("ordered", mode = "function") else factor)
		. . .
	Dumped
	S> 

If you do

	S> rr <- (if(T) get("ordered", mode = "function") else factor)
	S> rr
is the  ordered(.) function as it should and there doesn't seem to be a
problem if I do the things in  top-level [i.e. on the command line].

---
what's the problem in S ?

Martin Maechler <maechler@stat.math.ethz.ch>			<><
Seminar fuer Statistik, ETH-Zentrum SOL G1;	Sonneggstr.33
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1086
http://www.stat.math.ethz.ch/~maechler/
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel 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-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._