我有一个看起来像这样的数据集,但要大得多
x.col<-c(1,1,1,1,2,2,2,3,3,4)
y.col<-c(2,3,4,5,3,4,5,4,5,5)
response<-c(1,0,1,1,1,1,0,0,0,0)
ds<-data.frame(cbind(x.col,y.col,response))
根据这些数据,我想创建一个矩阵,其中行和列相同,单元格中的值表示 x 和 y 之间的响应。输出将如下所示:
one<-c(NA,1,0,1,1)
two<-c(1,NA,1,1,0)
three<-c(0,1,NA,0,0)
four<-c(1,1,0,NA,0)
five<-c(1,0,0,0,NA)
mx<-cbind(one,two,three,four,five)
row.names(mx)<-c(1,2,3,4,5)
colnames(mx)<-c(1,2,3,4,5)
请注意,对角线是“NA”,因为它们指的是 x 和 y 值相同的单元格
最佳答案
这是使用 xtabs
的另一种方法(虽然我更喜欢@akruns)
levs <- unique(unlist(ds[1:2])) # Find all the unique levels
Res <- as.data.frame.matrix(xtabs(response ~ factor(x.col, levs) + factor(y.col, levs), ds))
Res[lower.tri(Res)] <- t(Res)[lower.tri(Res)]
diag(Res) <- NA
all.equal(as.matrix(Res), mx)
## [1] TRUE
关于r - 为列和行创建具有匹配 x 和 y 标签的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29653418/