我是R的初学者。我有一系列有关已婚人士姓氏的数据。
Id_mar Wife Husband
1 1 Smith Johnson
2 2 Smith Carter
3 3 White Carter
4 4 Wang Smith
5 5 White Carter
我需要以方矩阵的形式获取它(以便能够以各种方式对其进行操作)。因此,我想我必须首先将其转换为:
data.melt<-melt(dat.mar,id=c('Wife','Husband'))
dat.melt$value<-1
dat.cast<-cast(dat.melt, Wife~Husband, length)
Wife Carter Johnson Smith
1 Smith 1 1 0
2 Wang 0 0 1
3 White 2 0 0
然后将其转换为矩阵:
dat.mat<-as.matrix(dat.cast)
Carter Johnson Smith
Smith 1 1 0
Wang 0 0 1
White 2 0 0
但是现在,如何准确地添加列和行,以使行和列以正确的字母顺序得到方矩阵?看起来像这样:
Carter Johnson Smith Wang White
Carter 0 0 0 0 0
Johnson 0 0 0 0 0
Smith 1 1 0 0 0
Wang 0 0 1 0 0
White 2 0 0 0 0
基于预期的输出,我们可以table
对factor
转换的“妻子”和“丈夫”列使用(如评论中提到的@David Arenburg),同时将列levels
的sort
edunique
元素指定为ed元素(“ Un1”)
Un1 <- sort(unique(unlist(df1[-1])))
table(factor(df1$Wife, levels=Un1), factor(df1$Husband, levels=Un1))
# Carter Johnson Smith Wang White
# Carter 0 0 0 0 0
# Johnson 0 0 0 0 0
# Smith 1 1 0 0 0
# Wang 0 0 1 0 0
# White 2 0 0 0 0
或者我们可以使用mtabulate
from qdapTools
。
library(qdapTools)
mtabulate(as.data.frame(t(df1[-1])))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句