是否有一个R函数用于制作单选题的列联表?
我只需要为一个有多项选择的问题做一个交叉表 我有一个调查结果。这样做的目的是让了解品牌的人也了解其他品牌 假设我们有一个包含答案的输入表:是否有一个R函数用于制作单选题的列联表?,r,R,我只需要为一个有多项选择的问题做一个交叉表 我有一个调查结果。这样做的目的是让了解品牌的人也了解其他品牌 假设我们有一个包含答案的输入表: Id Brand1 Brand2 Brand3 Brand4 1 1 1 0 1 2 0 0 1 1 3 1 1 0 0 4 1 0 0 1 5 0 0 1
Id Brand1 Brand2 Brand3 Brand4
1 1 1 0 1
2 0 0 1 1
3 1 1 0 0
4 1 0 0 1
5 0 0 1 1
6 0 0 1 0
7 1 1 0 1
我们制作一个交叉表,列出每个品牌的答案总和:
Brand1 Brand2 Brand3 Brand4
Brand1 4 3 0 3
Brand2 3 3 0 2
Brand3 0 0 3 2
Brand4 3 2 2 5
Brand1 Brand2 Brand3 Brand4
Brand1 100% 100% 0% 60%
Brand2 75% 100% 0% 40%
Brand3 0% 0% 100% 40%
Brand4 75% 67% 67% 100%
然后从所有了解每个品牌的人中计算列百分比:
Brand1 Brand2 Brand3 Brand4
Brand1 4 3 0 3
Brand2 3 3 0 2
Brand3 0 0 3 2
Brand4 3 2 2 5
Brand1 Brand2 Brand3 Brand4
Brand1 100% 100% 0% 60%
Brand2 75% 100% 0% 40%
Brand3 0% 0% 100% 40%
Brand4 75% 67% 67% 100%
数据
d = structure(list(Id = 1:7,
Brand1 = c(1L, 0L, 1L, 1L, 0L, 0L, 1L),
Brand2 = c(1L, 0L, 1L, 0L, 0L, 0L, 1L),
Brand3 = c(0L, 1L, 0L, 0L, 1L, 1L, 0L),
Brand4 = c(1L, 1L, 0L, 1L, 1L, 0L, 1L)),
class = "data.frame",
row.names = c(NA, -7L))
数据
d = structure(list(Id = 1:7,
Brand1 = c(1L, 0L, 1L, 1L, 0L, 0L, 1L),
Brand2 = c(1L, 0L, 1L, 0L, 0L, 0L, 1L),
Brand3 = c(0L, 1L, 0L, 0L, 1L, 1L, 0L),
Brand4 = c(1L, 1L, 0L, 1L, 1L, 0L, 1L)),
class = "data.frame",
row.names = c(NA, -7L))
我们可以用矩阵乘法来实现。使用d.b.的数据:
dmat = as.matrix(d[-1])
count = t(dmat) %*% dmat
count
# Brand1 Brand2 Brand3 Brand4
# Brand1 4 3 0 3
# Brand2 3 3 0 2
# Brand3 0 0 3 2
# Brand4 3 2 2 5
apply(count, 2, function(x) x / max(x))
# Brand1 Brand2 Brand3 Brand4
# Brand1 1.00 1.0000000 0.0000000 0.6
# Brand2 0.75 1.0000000 0.0000000 0.4
# Brand3 0.00 0.0000000 1.0000000 0.4
# Brand4 0.75 0.6666667 0.6666667 1.0
我们可以用矩阵乘法来实现。使用d.b.的数据:
dmat = as.matrix(d[-1])
count = t(dmat) %*% dmat
count
# Brand1 Brand2 Brand3 Brand4
# Brand1 4 3 0 3
# Brand2 3 3 0 2
# Brand3 0 0 3 2
# Brand4 3 2 2 5
apply(count, 2, function(x) x / max(x))
# Brand1 Brand2 Brand3 Brand4
# Brand1 1.00 1.0000000 0.0000000 0.6
# Brand2 0.75 1.0000000 0.0000000 0.4
# Brand3 0.00 0.0000000 1.0000000 0.4
# Brand4 0.75 0.6666667 0.6666667 1.0