附加频率表 - 带有缺失值
Appending Frequency Tables - With Missing Values
目标是生成我选择的所有变量(关于 4 份报纸的阅读习惯)的频率 table,这些变量本质上具有相同的可能值:
1= Subscribed
2= Every week
3= Sometimes
4= Never
0= NA (No Answers)
如果其中一个变量不包含可能的值之一,就会出现问题。例如,如果没有人订阅该特定报纸。
a <- c(1,2,3,4,3,1,2,3,4,3)
b <- c(2,2,3,4,3,0,0,3,4,1)
d <- c(2,2,3,4,3,0,0,0,0,0)
e <- c(3,3,3,3,3,3,3,3,3,3)
ta <- table(a)
tb <- table(b)
td <- table(d)
te <- table(e)
abde <- cbind(ta,tb,td,te)
ta tb td te
0 2 2 5 10
1 2 1 2 10
2 4 2 2 10
3 2 3 1 10
4 2 2 5 10
零频率被最后一个值的副本替换。
如何以更好的方式实现这一目标?
我想你在找 factor
:
> L <- list(a, b, d, e)
> A <- sort(unique(unlist(L, use.names = FALSE)))
> sapply(L, function(x) table(factor(x, A)))
[,1] [,2] [,3] [,4]
0 0 2 5 0
1 2 1 0 0
2 2 2 2 0
3 4 3 2 10
4 2 2 1 0
更新
这里有一个基础 R 的方法可能更直接:
> L <- mget(c("a", "b", "d", "e"))
> table(stack(L))
ind
values a b d e
0 0 2 5 0
1 2 1 0 0
2 2 2 2 0
3 4 3 2 10
4 2 2 1 0
这类似于@Anandas 的解决方案(我会post因为已经在写了)
df <- data.frame(a, b, d, e)
do.call(cbind, lapply(df, function(x) table(factor(x, levels = 0:4))))
# a b d e
# 0 0 2 5 0
# 1 2 1 0 0
# 2 2 2 2 0
# 3 4 3 2 10
# 4 2 2 1 0
您可以使用 qdapTools
中的 mtabulate
library(qdapTools)
t(mtabulate(list(a,b,d,e)))
# [,1] [,2] [,3] [,4]
#0 0 2 5 0
#1 2 1 0 0
#2 2 2 2 0
#3 4 3 2 10
#4 2 2 1 0
或者
t(mtabulate(data.frame(a,b,d,e)))
# a b d e
#0 0 2 5 0
#1 2 1 0 0
#2 2 2 2 0
#3 4 3 2 10
#4 2 2 1 0
目标是生成我选择的所有变量(关于 4 份报纸的阅读习惯)的频率 table,这些变量本质上具有相同的可能值:
1= Subscribed
2= Every week
3= Sometimes
4= Never
0= NA (No Answers)
如果其中一个变量不包含可能的值之一,就会出现问题。例如,如果没有人订阅该特定报纸。
a <- c(1,2,3,4,3,1,2,3,4,3)
b <- c(2,2,3,4,3,0,0,3,4,1)
d <- c(2,2,3,4,3,0,0,0,0,0)
e <- c(3,3,3,3,3,3,3,3,3,3)
ta <- table(a)
tb <- table(b)
td <- table(d)
te <- table(e)
abde <- cbind(ta,tb,td,te)
ta tb td te
0 2 2 5 10
1 2 1 2 10
2 4 2 2 10
3 2 3 1 10
4 2 2 5 10
零频率被最后一个值的副本替换。
如何以更好的方式实现这一目标?
我想你在找 factor
:
> L <- list(a, b, d, e)
> A <- sort(unique(unlist(L, use.names = FALSE)))
> sapply(L, function(x) table(factor(x, A)))
[,1] [,2] [,3] [,4]
0 0 2 5 0
1 2 1 0 0
2 2 2 2 0
3 4 3 2 10
4 2 2 1 0
更新
这里有一个基础 R 的方法可能更直接:
> L <- mget(c("a", "b", "d", "e"))
> table(stack(L))
ind
values a b d e
0 0 2 5 0
1 2 1 0 0
2 2 2 2 0
3 4 3 2 10
4 2 2 1 0
这类似于@Anandas 的解决方案(我会post因为已经在写了)
df <- data.frame(a, b, d, e)
do.call(cbind, lapply(df, function(x) table(factor(x, levels = 0:4))))
# a b d e
# 0 0 2 5 0
# 1 2 1 0 0
# 2 2 2 2 0
# 3 4 3 2 10
# 4 2 2 1 0
您可以使用 qdapTools
mtabulate
library(qdapTools)
t(mtabulate(list(a,b,d,e)))
# [,1] [,2] [,3] [,4]
#0 0 2 5 0
#1 2 1 0 0
#2 2 2 2 0
#3 4 3 2 10
#4 2 2 1 0
或者
t(mtabulate(data.frame(a,b,d,e)))
# a b d e
#0 0 2 5 0
#1 2 1 0 0
#2 2 2 2 0
#3 4 3 2 10
#4 2 2 1 0