[datatable-help] Character matrix conversion generating factors as columns?

Alexandre Sieira alexandre.sieira at gmail.com
Tue Jun 25 18:09:51 CEST 2013


I was trying to convert a character matrix to a data.table with character columns, but got them all as factors instead. Is that to be expected?

> m = matrix(rep("hello", 9), ncol=3)
> m
     [,1]    [,2]    [,3]   
[1,] "hello" "hello" "hello"
[2,] "hello" "hello" "hello"
[3,] "hello" "hello" "hello"
> library(data.table)
data.table 1.8.8  For help type: help("data.table")
> str(data.table(m))
Classes ‘data.table’ and 'data.frame':	3 obs. of  3 variables:
 $ V1: Factor w/ 1 level "hello": 1 1 1
 $ V2: Factor w/ 1 level "hello": 1 1 1
 $ V3: Factor w/ 1 level "hello": 1 1 1
 - attr(*, ".internal.selfref")=<externalptr> 

I ended up doing something ugly like this to solve it:

> str(data.table(data.frame(m, stringsAsFactors=F)))
Classes ‘data.table’ and 'data.frame':	3 obs. of  3 variables:
 $ X1: chr  "hello" "hello" "hello"
 $ X2: chr  "hello" "hello" "hello"
 $ X3: chr  "hello" "hello" "hello"
 - attr(*, ".internal.selfref")=<externalptr> 

I couldn't find any equivalent to 'stringsAsFactors' on the data.table documentation. Is there a better way to do this?

-- 
Alexandre Sieira
CISA, CISSP, ISO 27001 Lead Auditor

"The truth is rarely pure and never simple."
Oscar Wilde, The Importance of Being Earnest, 1895, Act I
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20130625/e849a2e3/attachment.html>


More information about the datatable-help mailing list