72

以下にdata.frame示すように、数値変数と因子変数で構成されています。

testFrame <- data.frame(First=sample(1:10, 20, replace=T),
           Second=sample(1:20, 20, replace=T), Third=sample(1:10, 20, replace=T),
           Fourth=rep(c("Alice","Bob","Charlie","David"), 5),
           Fifth=rep(c("Edward","Frank","Georgia","Hank","Isaac"),4))

matrix因子にダミー変数を割り当て、数値変数をそのままにしておく a を構築したいと考えています。

model.matrix(~ First + Second + Third + Fourth + Fifth, data=testFrame)

予想どおり、lmこれを実行すると、各因子の 1 つのレベルが参照レベルとして除外されます。matrixただし、すべての要因のすべてのレベルに対してダミー/指標変数を使用して構築したいと考えています。私はこの行列を構築してglmnetいるので、多重共線性について心配していません。

model.matrix因子のすべてのレベルに対してダミーを作成する方法はありますか?

4

11 に答える 11

71

(自分自身を償還しようとしています...)自動化に関する@Fabiansの回答に対するJaredのコメントに応じて、指定する必要があるのはコントラストマトリックスの名前付きリストだけであることに注意してください。contrasts()ベクトル/係数を取り、それから対比行列を生成します。このために、データセットの各要素でlapply()実行するために使用できます。たとえば、提供されている例の場合:contrasts()testFrame

> lapply(testFrame[,4:5], contrasts, contrasts = FALSE)
$Fourth
        Alice Bob Charlie David
Alice       1   0       0     0
Bob         0   1       0     0
Charlie     0   0       1     0
David       0   0       0     1

$Fifth
        Edward Frank Georgia Hank Isaac
Edward       1     0       0    0     0
Frank        0     1       0    0     0
Georgia      0     0       1    0     0
Hank         0     0       0    1     0
Isaac        0     0       0    0     1

@fabiansの回答にうまく収まるもの:

model.matrix(~ ., data=testFrame, 
             contrasts.arg = lapply(testFrame[,4:5], contrasts, contrasts=FALSE))
于 2010-12-31T09:26:23.613 に答える
54

contrasts因子変数の をリセットする必要があります。

model.matrix(~ Fourth + Fifth, data=testFrame, 
        contrasts.arg=list(Fourth=contrasts(testFrame$Fourth, contrasts=F), 
                Fifth=contrasts(testFrame$Fifth, contrasts=F)))

または、タイピングを少し減らし、適切な名前を付けずに:

model.matrix(~ Fourth + Fifth, data=testFrame, 
    contrasts.arg=list(Fourth=diag(nlevels(testFrame$Fourth)), 
            Fifth=diag(nlevels(testFrame$Fifth))))
于 2010-12-30T09:38:21.307 に答える
11

dummyVarsからcaretも使用できます。http://caret.r-forge.r-project.org/preprocess.html

于 2013-03-14T02:29:10.497 に答える
3

Ok。上記を読んで、すべてをまとめてください。線形予測子を取得するために係数ベクトルを乗算する 'X.factors' などの行列が必要だとします。まだいくつかの追加手順があります。

X.factors = 
  model.matrix( ~ ., data=X, contrasts.arg = 
    lapply(data.frame(X[,sapply(data.frame(X), is.factor)]),
                                             contrasts, contrasts = FALSE))

(因子列が 1 つしかない場合は、X[*] をデータ フレームに戻す必要があることに注意してください。)

次に、次のようなものが得られたとします。

attr(X.factors,"assign")
[1]  0  1  **2**  2  **3**  3  3  **4**  4  4  5  6  7  8  9 10 #emphasis added

各因子の **'d 参照レベルを取り除きたい

att = attr(X.factors,"assign")
factor.columns = unique(att[duplicated(att)])
unwanted.columns = match(factor.columns,att)
X.factors = X.factors[,-unwanted.columns]
X.factors = (data.matrix(X.factors))
于 2014-07-24T18:05:51.790 に答える
2

R パッケージ 'CatEncoders' の使用

library(CatEncoders)
testFrame <- data.frame(First=sample(1:10, 20, replace=T),
           Second=sample(1:20, 20, replace=T), Third=sample(1:10, 20, replace=T),
           Fourth=rep(c("Alice","Bob","Charlie","David"), 5),
           Fifth=rep(c("Edward","Frank","Georgia","Hank","Isaac"),4))

fit <- OneHotEncoder.fit(testFrame)

z <- transform(fit,testFrame,sparse=TRUE) # give the sparse output
z <- transform(fit,testFrame,sparse=FALSE) # give the dense output
于 2016-09-14T01:56:17.607 に答える
1

tidyverse各列を手動で指定せずにこれを実現するために使用できます。

秘訣は、「長い」データフレームを作成することです。

次に、いくつかのものを変更し、それを広げてインジケーター/ダミー変数を作成します。

コード:

library(tidyverse)

## add index variable for pivoting
testFrame$id <- 1:nrow(testFrame)

testFrame %>%
    ## pivot to "long" format
    gather(feature, value, -id) %>%
    ## add indicator value
    mutate(indicator=1) %>%
    ## create feature name that unites a feature and its value
    unite(feature, value, col="feature_value", sep="_") %>%
    ## convert to wide format, filling missing values with zero
    spread(feature_value, indicator, fill=0)

出力:

   id Fifth_Edward Fifth_Frank Fifth_Georgia Fifth_Hank Fifth_Isaac First_2 First_3 First_4 ...
1   1            1           0             0          0           0       0       0       0
2   2            0           1             0          0           0       0       0       0
3   3            0           0             1          0           0       0       0       0
4   4            0           0             0          1           0       0       0       0
5   5            0           0             0          0           1       0       0       0
6   6            1           0             0          0           0       0       0       0
7   7            0           1             0          0           0       0       1       0
8   8            0           0             1          0           0       1       0       0
9   9            0           0             0          1           0       0       0       0
10 10            0           0             0          0           1       0       0       0
11 11            1           0             0          0           0       0       0       0
12 12            0           1             0          0           0       0       0       0
...
于 2020-03-27T00:22:31.003 に答える