从非对称矩阵(或数据帧)到具有R的对称平方矩阵
给定此data.frame:“sample”,表示物种之间的成对赢和输:从非对称矩阵(或数据帧)到具有R的对称平方矩阵,r,dataframe,symmetric,R,Dataframe,Symmetric,给定此data.frame:“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") 如何修改“sample”,使其具有与rownames相同的列名,反之亦然,并用零填充添加的列或行,
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")
如何修改“sample”,使其具有与rownames相同的列名,反之亦然,并用零填充添加的列或行,以使数据帧对称,如下所示?(我更喜欢dataframe,因为我恐怕不擅长矩阵):
真正的数据大约有150行和150列,所以我真的不想要
使用excel手动执行此操作。此格式是应用有关竞争物种相互作用结果(列:赢,行:输)的一些其他函数所必需的。您显示的输出似乎不是对称矩阵,但如果所需的输出是您所寻找的,则有一种方法可以通过使用
stack
和xtabs
获得。制作“正方形”矩阵的关键是确保行和列名都是“因数”的
##提取行名和列名的唯一组合并对其排序。
##这将在创建我们的因子时使用。
名字
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
## 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