New codes() methods

Jonathan Rougier
Thu, 4 Nov 1999 11:23:44 +0000 (GMT)

Hi Everyone,

Can I suggest a couple of new `codes' methods.  I know codes is a bit
dodgy (at least, according to the comments in codes.factor), but for what
it's worth I like to extract codes from data frames of factors, for which
the following two functions (which operate recursively) are helpful:

"codes.default" <-
    if (is.list(x))
      lapply(x, codes)

"" <-
    row.names <- attr(x, "row.names")
    data.frame(codes(as.list(x)), row.names = row.names)

#### Hence:

lvl <- ordered(c("L", "H"), c("L", "H"))
llist <- rep(list(lvl), 4)
codes(llist)			# list of codes
expand.grid(llist)		# data frame of factors
codes(expand.grid(llist))	# data frame of codes

The non-list default behaviour is for data frames that mix factors with
other stuff: the usual codes(factor(1:10)) caveat (from the help file) 
still applies, of course!  Note that using codes on an array will produce
a vector as the dim attribute is lost, eg

codes(matrix(1:12, 3, 4))	# shocking!

but although I toyed with the idea of mapping matrices to data frames in
the default function I thought in the end that this was making a
presumption about the interpretation of the rows and columns that was not
justified.  After all, you could still do

codes(, 3, 4)))

if the presumption *was* justified.

Cheers, Jonathan.

Jonathan Rougier                       Science Laboratories
Department of Mathematical Sciences    South Road
University of Durham                   Durham DH1 3LE

"[B]egin upon the precept ... that the things we see are to be 
 weighed in the scale with what we know"  (Meredith, 1879, The Egoist)

r-devel mailing list -- Read
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: