交互表 - 与宠物和房屋的案例

交互表 - 与宠物和房屋的案例

我有一份房屋清单和一份动物物种清单。


houses = c(1,1,2,3,4,4,4,4,5,6,5)

animals = c('cat','dog','cat','dog','rat', 'cat', 'spider', 'snake', 'cat', 'cat', 'rat')

我正在尝试创建一个函数,该函数返回一个上三角表,指示每只宠物,它被观察到的生活在同一个房子中的次数比其他动物物种。是否有意义?


对于上面的例子,表应该是这样的(希望没有错!):


    dog   rat   spider   snake

cat  1     2      1        1      

dog        0      0        0

rat               1        1

spider                     1

注意:此函数应适用于任何两个相同长度的向量,无论它们是否包含数字或字符串


守候你守候我
浏览 552回答 2
2回答

料青山看我应如是

使用table和crossprod:out <- crossprod(table(houses, animals))out[lower.tri(out, diag=TRUE)] <- NAout#&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;animals# animals&nbsp; cat dog rat snake spider#&nbsp; &nbsp;cat&nbsp; &nbsp; &nbsp;NA&nbsp; &nbsp;1&nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp; 1#&nbsp; &nbsp;dog&nbsp; &nbsp; &nbsp;NA&nbsp; NA&nbsp; &nbsp;0&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp; 0#&nbsp; &nbsp;rat&nbsp; &nbsp; &nbsp;NA&nbsp; NA&nbsp; NA&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp; 1#&nbsp; &nbsp;snake&nbsp; &nbsp;NA&nbsp; NA&nbsp; NA&nbsp; &nbsp; NA&nbsp; &nbsp; &nbsp; 1#&nbsp; &nbsp;spider&nbsp; NA&nbsp; NA&nbsp; NA&nbsp; &nbsp; NA&nbsp; &nbsp; &nbsp;NA由于输出是a,matrix您可以NA直接在print以下位置禁止打印值:print(out,na.print="")#&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;animals# animals&nbsp; cat dog rat snake spider#&nbsp; &nbsp;cat&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp;2&nbsp; &nbsp; &nbsp;1&nbsp; &nbsp; &nbsp; 1#&nbsp; &nbsp;dog&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 0&nbsp; &nbsp; &nbsp;0&nbsp; &nbsp; &nbsp; 0#&nbsp; &nbsp;rat&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; &nbsp; 1#&nbsp; &nbsp;snake&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1#&nbsp; &nbsp;spider&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;

梵蒂冈之花

只需添加一个稀疏的替代方案,以防万一在制表期间可以减少任何内存占用:Matrix::crossprod(xtabs(~ houses + animals, sparse = TRUE))&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP