2012-09-25 47 views
2

鑑於這種data.frame:「樣本」,其表示成對輸贏物種間:從非對稱矩陣(或數據幀)到一個對稱方陣,其中R

 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 

如何修改「樣本」,使其具有相同的列名rownames,反之亦然,而在添加列或行填充的數據幀零是對稱的,看起來像如下所示? (我喜歡數據幀,因爲我怕我不擅長與矩陣):

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做手工。此格式需要應用有關競爭性物種相互作用結果的其他功能(列:勝,行:損失)。

回答

3

告訴你似乎不是一個對稱矩陣,但如果期望的輸出是你在找什麼,在這裏是一種方式,你可以通過使用stackxtabs得到它的輸出。製作「方形」矩陣的關鍵是確保行和列名稱是「分解的」。

## 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