11

ここでわかることから、data.table v1.8.0+ は文字列を自動的に因数に変換しないと思います。

具体的には、そのページから Matthew Dowle を引用します。

stringAsFactors は必要ありません。v1.8.0 では次のように行われます: o 文字列がキーで許可され、factor よりも優先されます。data.table() と setkey() はもはや文字を因数分解しません。因子は引き続きサポートされます。

私はそれを見ていません...これが私のRセッションのトランスクリプトです:

まず、data.table > 1.8.0 の十分な最新バージョンがあることを確認します。

> library(data.table)
data.table 1.8.8  For help type: help("data.table")

次に、2x2 の data.table を作成します。要因を作成することに注意してください...

> m <- matrix(letters[1:4], ncol=2)
> str(data.table(m))
Classes ‘data.table’ and 'data.frame':  2 obs. of  2 variables:
 $ V1: Factor w/ 2 levels "a","b": 1 2
 $ V2: Factor w/ 2 levels "c","d": 1 2
 - attr(*, ".internal.selfref")=<externalptr> 

data.frame() でstringAsFactorsを使用してからdata.table()を呼び出すと、すべてうまくいきます...

> str(data.table(data.frame(m, stringsAsFactors=FALSE)))
Classes ‘data.table’ and 'data.frame':  2 obs. of  2 variables:
 $ X1: chr  "a" "b"
 $ X2: chr  "c" "d"
 - attr(*, ".internal.selfref")=<externalptr> 

私は何が欠けていますか?data.frame() は文字列を要素に変換することになっていますか?もしそうなら、その動作をオフにする「より良い方法」はありますか?

ありがとう!

4

2 に答える 2

10

Update:

This issue seems to have slipped past somehow until now. Thanks to @fpinter for filing the issue recently. It is now fixed in commit 1322. From NEWS, No:39 under bug fixes for v1.9.3:

as.data.table.matrix does not convert strings to factors by default. data.table likes and prefers using character vectors to factors. Closes #745. Thanks to @fpinter for reporting the issue on the github issue tracker and to vijay for reporting here on SO.


It appears that this non-coercion is not yet implemented.

data.table deals with matrix arguments using as.data.table

if (is.matrix(xi) || is.data.frame(xi)) {
            xi = as.data.table(xi, keep.rownames = keep.rownames)
            x[[i]] = xi
            numcols[i] = length(xi)
        }

and

as.data.table.matrix

contains

if (mode(x) == "character") {
        for (i in ic) value[[i]] <- as.factor(x[, i])
    }

Might be worth reporting this to the bug tracker. (it is still implemented in 1.8.9, the current r-forge version)

于 2013-07-17T04:34:53.927 に答える
6

回避策として、@mnel の回答を完成させるために、data.frame のデフォルトの動作をオフにしたい場合は、専用オプションを使用できます。

options(stringsAsFactors=FALSE)

str(data.table(data.frame(m)))
Classes ‘data.table’ and 'data.frame':  2 obs. of  2 variables:
 $ X1: chr  "a" "b"
 $ X2: chr  "c" "d"
 - attr(*, ".internal.selfref")=<externalptr> 
于 2013-07-17T04:38:40.657 に答える