我是 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
(正如@David Arenburg 在评论中提到的)factor
转换后的“妻子”和“丈夫”列,指定levels
as the sort
ed unique
两列的元素 ('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])))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)