2 回答
TA贡献1772条经验 获得超8个赞
使用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
由于输出是a,matrix您可以NA直接在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
TA贡献1900条经验 获得超5个赞
只需添加一个稀疏的替代方案,以防万一在制表期间可以减少任何内存占用:Matrix::crossprod(xtabs(~ houses + animals, sparse = TRUE))
- 2 回答
- 0 关注
- 551 浏览
添加回答
举报