r - 从非对称矩阵(或数据帧)到具有 R 的对称方阵

标签 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")

应该是这样的:

    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手动完成。这种格式需要应用一些其他有关竞争物种相互作用结果的函数(列:胜利,行:损失)。

最佳答案

您显示的输出似乎不是对称 矩阵,但如果所需的输出是您正在寻找的,那么您可以通过使用 获得它的一种方法堆栈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 

关于r - 从非对称矩阵(或数据帧)到具有 R 的对称方阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12591708/

相关文章:

python - 计算滚动窗口中的不同字符串包括使用 Pandas 的 NaN

r - 从向量的循环移位创建对称矩阵

r - 如何生成对称随机矩阵?

matlab - 如何生成具有均匀分布条目的随机实对称方阵

r - 如何在 Shiny 中验证上传的 csv

python - 如何使 Pandas 中的行操作更快?目前发布代码需要 13 小时

r - 是否有 R 函数可以按列名的一部分创建子集?

r - R中的聚类分析期间"NAs introduced by coercion"

r - ggplot在分面时删除特定的x轴标签

删除 data.table 中的所有重复项,添加带有标识符列表的列