5

それで、私は R を 2 年間オンとオフを使い分けて、ベクトル化の全体的なアイデアを得ようとしてきました。私は調査の複数の回答セットからのダミー変数をよく扱っているので、このケースで学ぶのは興味深いと思いました。

アイデアは、複数の回答からダミー変数に (そして戻る) ことです。たとえば、「これらの 8 つの異なるチョコレートのうち、あなたのお気に入りのチョコレートはどれですか (3 つまで選択してください) ?」

場合によっては、これをダミー変数 ( 「コート ドール」が好きな人は1、嫌いな人は0 ) としてコーディングし、オプションごとに 1 つの変数を使用し、場合によってはカテゴリ ( 「コート ドール」が好きな人1 "「Lindt」が好きな人には2など)、3 つの選択肢に対して 3 つの変数があります。

したがって、基本的には、行が次のようなマトリックスになります

1,0,0,1,0,0,1,0

または、次のような行を持つマトリックス

1,4,7

そして、前述のように、アイデアはあるものから別のものへと移動することです。これまでのところ、各ケースのループ ソリューションと、ダミーからカテゴリに移行するためのベクトル化されたソリューションが得られました。この問題と、カテゴリーからダミーへのステップのベクトル化されたソリューションについてさらに掘り下げていただければ幸いです。

ダミーからダミーではない

vecOrig<-matrix(0,nrow=18,ncol=8)  # From this one
vecDest<-matrix(0,nrow=18,ncol=3)  # To this one

# Populating the original matrix.
# I'm pretty sure this could have been added to the definition of the matrix, 
# but I kept getting repeated numbers.
# How would you vectorize this?
for (i in 1:length(vecOrig[,1])){               
vecOrig[i,]<-sample(vec)
}

# Now, how would you vectorize this following step... 
for(i in 1:length(vecOrig[,1])){            
  vecDest[i,]<-grep(1,vecOrig[i,])
}

# Vectorized solution, I had to transpose it for some reason.
vecDest2<-t(apply(vecOrig,1,function(x) grep(1,x)))   

ダミーからダミーではない

matOrig<-matrix(0,nrow=18,ncol=3)  # From this one
matDest<-matrix(0,nrow=18,ncol=8)  # To this one.

# We populate the origin matrix. Same thing as the other case. 
for (i in 1:length(matOrig[,1])){         
  matOrig[i,]<-sample(1:8,3,FALSE)
}

# this works, but how to make it vectorized?
for(i in 1:length(matOrig[,1])){          
  for(j in matOrig[i,]){
    matDest[i,j]<-1
  }
}

# Not a clue of how to vectorize this one. 
# The 'model.matrix' solution doesn't look neat.
4

2 に答える 2

4

ベクトル化されたソリューション:

ダミーからダミーではない

vecDest <- t(apply(vecOrig == 1, 1, which))

ダミーからダミーへ(元に戻す)

nCol <- 8

vecOrig <- t(apply(vecDest, 1, replace, x = rep(0, nCol), values = 1))
于 2012-12-18T15:32:48.680 に答える
0

これは、最初の部分の内部を提供する可能性があります。

#Create example data
set.seed(42)
vecOrig<-matrix(rbinom(20,1,0.2),nrow=5,ncol=4)

     [,1] [,2] [,3] [,4]
[1,]    1    0    0    1
[2,]    1    0    0    1
[3,]    0    0    1    0
[4,]    1    0    0    0
[5,]    0    0    0    0

これは、各行の1の数が等しいことを前提としないことに注意してください(たとえば、「3つまで選択」と書いた場合)。

#use algebra to create position numbers
vecDest <- t(t(vecOrig)*1:ncol(vecOrig))

     [,1] [,2] [,3] [,4]
[1,]    1    0    0    4
[2,]    1    0    0    4
[3,]    0    0    3    0
[4,]    1    0    0    0
[5,]    0    0    0    0

ここで、ゼロを削除します。したがって、オブジェクトをリストに変換する必要があります。

vecDest <- split(t(vecDest), rep(1:nrow(vecDest), each = ncol(vecDest)))
lapply(vecDest,function(x) x[x>0])

$`1`
[1] 1 4

$`2`
[1] 1 4

$`3`
[1] 3

$`4`
[1] 1

$`5`
numeric(0)
于 2012-12-18T15:37:40.637 に答える