[R] Stack with factors

Peter Ehlers ehlers at ucalgary.ca
Thu Apr 1 12:33:19 CEST 2010


On 2010-04-01 3:53, Ken Knoblauch wrote:
> Kenneth Roy Cabrera Torres<krcabrer<at>  une.net.co>  writes:
>> Hi R users:
>> I found that I cannot stack() a data.frame with factors.
>> db1<-data.frame(replicate(6,factor(sample(c("A","B"),6,replace=TRUE))))
>> str(db1)
>> db2<-stack(db1)
>> db2
>> "db2" does not have any row.
>> How can I stack them by the variables X1,X2,...,X6?
>
> you can see what is happening in stack.data.frame
> you have a line
>
> x<- x[, unlist(lapply(x, is.vector)), drop = FALSE]
>
> and
>
> lapply(x, is.vector))
>
> is applied to each column of the data frame but
> you can verify for yourself that a factor yields FALSE here
>
> x<- db1[[1]]
> is.vector(x)
> [1] FALSE
>
> so I think that this at least explains why it doesn't work as
> you expected.

db2 <- stack(lapply(db1, as.character))

will do it.

  -Peter Ehlers

>
>> Thank you for your help.
>>
>> Kenneth
>
>

-- 
Peter Ehlers
University of Calgary



More information about the R-help mailing list