互动表 - 带有宠物和房屋的案例 [英] Table of Interactions - Case with pets and houses
问题描述
我有一份房屋清单和一份动物种类清单.
I have a list of houses and a list of animal species.
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')
我正在尝试创建一个函数,该函数返回一个上三角表,该表指示每只宠物,观察到它与其他动物物种住在同一屋子里的次数.有意义吗?
I am trying to create a function that returns an upper triangular table that indicates for each pet, the number of times that it was observed to live in the same house than the other animal species. Does it make sense?
对于上面的例子,表格应该是这样的(希望没有出错!):
For the above example, the table should look like this (hope there's no mistake!) :
dog rat spider snake
cat 1 2 1 1
dog 0 0 0
rat 1 1
spider 1
<小时>
注意:这个函数应该适用于任何两个长度相同的向量,无论它们是否包含数字或字符串
Note: This function should work for any two vectors of same lengths, whatever if they contain numbers or string
推荐答案
使用table
和crossprod
:
out <- crossprod(table(houses, animals))
out[lower.tri(out, diag=TRUE)] <- NA
out
# animals
# animals cat dog rat snake spider
# cat NA 1 2 1 1
# dog NA NA 0 0 0
# rat NA NA NA 1 1
# snake NA NA NA NA 1
# spider NA NA NA NA NA
由于输出是 matrix
,您可以直接在 print
中抑制 NA
值的打印:
Since the output is a matrix
you can suppress the printing of the NA
values directly in print
:
print(out,na.print="")
# animals
# animals cat dog rat snake spider
# cat 1 2 1 1
# dog 0 0 0
# rat 1 1
# snake 1
# spider
这篇关于互动表 - 带有宠物和房屋的案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!