2

このdata.frameが与えられた場合:'サンプル'、これは種間のペアワイズの勝ち負けを表します:

     sp1<-c(0,1,0)
     sp3<-c(1,2,2)
     sp5<-c(3,1,0)
     sample<-as.data.frame(cbind(sp1,sp3,sp5))
     rownames(sample)<-c("sp1","sp6","sp8")

これは次のようになります。

    sp1 sp3 sp5
sp1   0   1   3
sp6   1   2   1
sp8   0   2   0

'sample'を変更して、行名と同じ列名になるようにするにはどうすればよいですか。また、その逆で、データフレームが対称になり、次のようになるように、追加された列または行にゼロを入力するにはどうすればよいですか。(私は行列が苦手なので、データフレームを好みます):

    sp1 sp3 sp5 sp6 sp8
sp1   0   1   3   0   0
sp3   0   0   0   0   0
sp5   0   0   0   0   0
sp6   1   2   1   0   0
sp8   0   1   0   0   0

実際のデータには約150の行と列があるため、Excelを使用して手動で実行することはあまりありません。この形式は、競合する種の相互作用の結果に関する他の関数を適用するために必要です(列:勝ち、行:負け)。

4

1 に答える 1

3

表示されている出力は対称行列ではないようですが、目的の出力が探しているものである場合は、 と を使用して取得する方法の 1 つをstack次に示しますxtabs。「正方」行列を作成するための鍵は、行と列の名前が「因数分解」されていることを確認することです。

## Extract and sort the unique combination of row and column names.
## This will be used when creating our factors.
NAMES <- sort(unique(c(rownames(sample), colnames(sample))))
## "stack" your data.frame, reintroducing the rownames
##   which get dropped in the stacking process
temp <- data.frame(rows = rownames(sample), stack(sample))
## Your stacked data looks like this:
temp
#   rows values ind
# 1  sp1      0 sp1
# 2  sp6      1 sp1
# 3  sp8      0 sp1
# 4  sp1      1 sp3
# 5  sp6      2 sp3
# 6  sp8      2 sp3
# 7  sp1      3 sp5
# 8  sp6      1 sp5
# 9  sp8      0 sp5

## Factor the row and column names
temp$rows <- factor(temp$rows, NAMES)
temp$ind <- factor(temp$ind, NAMES)

## Use xtabs to get your desired output. Wrap it in
##    as.data.frame.matrix to get a data.frame as output
as.data.frame.matrix(xtabs(values ~ rows + ind, temp))
#     sp1 sp3 sp5 sp6 sp8
# sp1   0   1   3   0   0
# sp3   0   0   0   0   0
# sp5   0   0   0   0   0
# sp6   1   2   1   0   0
# sp8   0   2   0   0   0 
于 2013-03-21T16:39:32.790 に答える