[R] building a data.frame from a matrix: preventing conversion to factors

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 14 07:59:26 CET 2007


On Wed, 14 Nov 2007, Christian Gold wrote:

> Thanks for your reply. I have tried the reproducible example you have 
> provided (thanks!) in 3 different versions of R, and get what you get in R 
> version 2.5.1, but in 2.3.1 (which I normally use) and 2.1.0 (which I still 
> have installed) I get factors.
> I guess this means I should switch to the new version?

Yes.  stringsAsFactors is relatively new (R 2.4.0).

>
> Christian
>
>
> Prof Brian Ripley wrote:
>> I am trying to build a data.frame from some vectors and some matrices
>> and seem to be unable to find out how to do this without converting
>> everything to factors.
>> I can prevent conversion of the vectors by using I(), as explained in
>> help(data.frame). However, this doesn't help with the matrices: if I try
>> I() with the matrix, the matrix gets incorporated into the data frame as
>> a whole, rather than as a list of vectors as it should be. ("as.is=T"
>> doesn't help either, and neither does "options(stringsAsFactors = FALSE)".)
>> 
>> I think we need the reproducible example we asked for.  I get
>> 
>>> z <- matrix(letters[1:12], 4, 3)
>>> z2 <- data.frame(x=1:4, z=z, stringsAsFactors=FALSE)
>>> sapply(z2, class)
>>           x         z.1         z.2         z.3
>>   "integer" "character" "character" "character"
>> 
>> so it is working as documented.  (BTW, using I() on a matrix is intended to 
>> insert a matrix as a single entity, and as.is is not an argument to 
>> data.frame.)
>> 
>

-- 
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-help mailing list