R多个分类变量的频率表

时间:2016-02-05 12:05:26

标签: r dplyr plyr frequency summary

我已将SPSS .SAV文件中的采访数据导入为data.frame,现在我正在尝试根据问题编号和访谈位置创建频率表。这是一个例子data.frame

loc<-c("city1","city2","city1","city2","city1","city1","city2","city2","city1","city2")
q1<-c("YES","YES","NO","MAYBE","NO","NO","YES","NO","MAYBE","MAYBE")
q2<-c("YES","NO","MAYBE","YES","NO","MAYBE","MAYBE","YES","YES","NO")
q3<-c("NO","NO","NO","NO","YES","YES","MAYBE","MAYBE","NO","MAYBE")
df<-data.frame(loc,q1,q2,q3)

df
     loc    q1    q2    q3
1  city1   YES   YES    NO
2  city2   YES    NO    NO
3  city1    NO MAYBE    NO
4  city2 MAYBE   YES    NO
5  city1    NO    NO   YES
6  city1    NO MAYBE   YES
7  city2   YES MAYBE MAYBE
8  city2    NO   YES MAYBE
9  city1 MAYBE   YES    NO
10 city2 MAYBE    NO MAYBE

现在,我想根据问题编号"YES","NO","MAYBE"和位置"q1","q2","q3"计算每个答案选项"city1","city"的出现次数。生成的data.frame应如下所示:

   loc quest  answ freq
1  city1    q1   YES    1
2  city1    q1    NO    3
3  city1    q1 MAYBE    1
4  city2    q1   YES    2
5  city2    q1    NO    1
6  city2    q1 MAYBE    2
7  city1    q2   YES    2
8  city1    q2    NO    1
9  city1    q2 MAYBE    2
10 city2    q2   YES    2
11 city2    q2    NO    2
12 city2    q2 MAYBE    1
13 city1    q3   YES    2
14 city1    q3    NO    3
15 city1    q3 MAYBE    0
16 city2    q3   YES    0
17 city2    q3    NO    2
18 city2    q3 MAYBE    3

到目前为止,我已经使用了来自count()套餐的ddply()summarise()plyr,但没有运气。我当前的解决方案非常简洁,需要将df拆分为loc,创建一个包含as.data.frame(summary(df_city1))的频率表,从摘要字符串中检索频率并合并摘要data.frame city1city2重新组合在一起。我想必须有一个更容易/更优雅的解决方案。

1 个答案:

答案 0 :(得分:2)

我们转换广泛的数据集&#39;长期&#39; (gather执行此操作),然后group_by)&#39;定位&#39;任务&#39;,&#39;回答&#39;,然后使用{{1}得到计数。但是,如果我们要查找数据集中未找到的组合计数为0,那么我们可能需要连接具有三列tallyunique的所有complete组合的数据集。 unique这样做)。

library(dplyr)
library(tidyr)
dfN <- gather(df, quest, answ, q1:q3) %>%
                   complete(loc, quest, answ) %>%
                   unique()

res <- gather(df, quest, answ, q1:q3) %>%
               group_by(loc, quest, answ) %>%
               tally() %>%
               left_join(dfN, .) %>%
               mutate(n = ifelse(is.na(n), 0, n))
res
#     loc quest  answ     n
#   (fctr) (chr) (chr) (dbl)
#1   city1    q1 MAYBE     1
#2   city1    q1    NO     3
#3   city1    q1   YES     1
#4   city1    q2 MAYBE     2
#5   city1    q2    NO     1
#6   city1    q2   YES     2
#7   city1    q3 MAYBE     0
#8   city1    q3    NO     3
#9   city1    q3   YES     2
#10  city2    q1 MAYBE     2
#11  city2    q1    NO     1
#12  city2    q1   YES     2
#13  city2    q2 MAYBE     1
#14  city2    q2    NO     2
#15  city2    q2   YES     2
#16  city2    q3 MAYBE     3
#17  city2    q3    NO     2
#18  city2    q3   YES     0