将不对称的矩阵(或数据框)转换为R中的对称方阵

3

给定这个数据框:'sample',它代表物种间的成对胜负:

     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

我该如何修改“示例”数据框,使其具有与行名相同的列名,反之亦然,并且填充添加的列或行以零,以使数据框对称并看起来像下面所示?(我更喜欢使用数据框,因为我不太擅长矩阵):
    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手动操作。这种格式需要应用一些关于竞争物种相互作用结果的其他函数(列:wins, 行: losses)。

1个回答

4
您展示的输出看起来并不像是一个对称矩阵,但如果您需要的输出正是这样,以下是一种使用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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接