From p.dalgaard at biostat.ku.dk  Mon Aug 24 23:36:56 2009
From: p.dalgaard at biostat.ku.dk (Peter Dalgaard)
Date: Mon, 24 Aug 2009 23:36:56 +0200
Subject: [Rd] nchar on factors
In-Reply-To: <8b356f880908241419w53a6c85ej37cfc39660265071@mail.gmail.com>
References: <8b356f880908241419w53a6c85ej37cfc39660265071@mail.gmail.com>
Message-ID: <4A9307F8.8080406@biostat.ku.dk>

Stavros Macrakis wrote:
> In R 2.9.1 Windows:
> 
>> nchar(factor(paste('sdf',1:10)))
>  [1] 1 1 1 1 1 1 1 1 2 1
> 
> so it appears that nchar is counting the number of characters in the numeric
> representation, just like:
> 
>> nchar(as.numeric(factor(paste('sdf',1:10))))
>  [1] 1 1 1 1 1 1 1 1 2 1
> 
> but ?nchar says explicitly:
> 
>      x: character vector, or a vector to be coerced to a character
>           vector.
>      ...
>      The internal equivalent of the default method of 'as.character' is
>      performed on 'x' (so there is no method dispatch).
> 
> This would seem to say that nchar should behave the same as:
> 
>> nchar(as.character(factor(paste('sdf',1:10))))
>  [1] 5 5 5 5 5 5 5 5 5 6
> 
> Either the documentation or the code should be corrected.  Personally, I'd
> find the documented behavior much more useful, but I suppose that there is
> existing code that depends on the implementation's behavior rather than the
> specification.

The documentation has:

 >>
The internal equivalent of the default method of as.character is 
performed on x (so there is no method dispatch). If you want to operate 
on non-vector objects passing them through deparse first will be required.
<<

and (notice the no method dispatch bit)

 > as.character(unclass(factor(LETTERS)))
  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11" "12" "13" 
"14" "15"
[16] "16" "17" "18" "19" "20" "21" "22" "23" "24" "25" "26"

So, the documentation does appear to be in sync with the code (useful or 
not).


-- 
    O__  ---- Peter Dalgaard             ?ster Farimagsgade 5, Entr.B
   c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
  (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907



[Rd] nchar on factors
Peter Dalgaard