附加频率表 - 缺少值

时间:2015-02-12 19:02:46

标签: r frequency

目标是制作一个频率表,列出我所选择的所有变量(关于4种报纸的阅读习惯),这些变量本质上具有相同的可能值:

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

零频率被最后一个值的副本替换。

如何以更好的方式实现这一目标?

3 个答案:

答案 0 :(得分:4)

我认为您正在寻找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

答案 1 :(得分:3)

您可以使用mtabulate

中的qdapTools
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

答案 2 :(得分:2)

这类似于@Anandas解决方案(我会发布它,因为它已经在写作的中间)

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