[Rd] as.character on list (was read.table with ":" in column names)

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Jan 20 14:12:26 CET 2006


On Fri, 20 Jan 2006, Peter Dalgaard wrote:

[...]

> Yes, this is a bit nasty, but... What is happening is similar to this:
>
>> d <- data.frame(a=factor(LETTERS), b=factor(letters))
>> d[1,]
>  a b
> 1 A a
>> as.character(d[1,])
> [1] "1" "1"
>> as.character(d[1,1])
> [1] "A"
>> as.character(d[1,1,drop=F])
> [1] "1"
>
> or this:
>
>> l <- list(a=factor("x"),b=factor("y"))
>> l
> $a
> [1] x
> Levels: x
>
> $b
> [1] y
> Levels: y
>
>> as.character(l)
> [1] "1" "1"
>
> The thing is that as.character on a list will first coerce factors to
> numeric, then numeric to character.

Nope.  It just coerces an INTSXP to a STRSXP.  as.character (and all other 
forms of coercion that I can think of quickly) ignores classes except when 
initially dispatching.

Note that these examples are special cases:

> as.character(d[1:2,])
[1] "c(1, 2)" "c(1, 2)"

may also be unexpected but follows from the general (undocumented, I 
dare say) rules.

> I'm not sure whether there could be a rationale for it, but it isn't 
> S-PLUS compatible (not 6.2.1 anyway, which is the most recent one that I 
> have access to).

My S-PLUS deparses:

> l <- list(a=factor("x"),b=factor("y"))
> as.character(l)
[1] "structure(.Data = 1, .Label = \"x\", class = \"factor\")"
[2] "structure(.Data = 1, .Label = \"y\", class = \"factor\")"

which seems no better (and probably worse).

The only other consistent option I can see is for all coercion methods to 
dispatch at each element of a recursive object, which I suspect introduces 
a considerable overhead for very little gain.

One could perhaps argue for a data.frame method, since coercion operations 
on dataframes are rare and that is a case where people get factors where 
they wanted character columns.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list