R中有几个变量的频率表

时间:2012-08-07 19:02:43

标签: r aggregate frequency

我正在尝试复制官方统计中经常使用的表,但到目前为止还没有成功。给定像这样的数据框:

d1 <- data.frame( StudentID = c("x1", "x10", "x2", 
                          "x3", "x4", "x5", "x6", "x7", "x8", "x9"),
             StudentGender = c('F', 'M', 'F', 'M', 'F', 'M', 'F', 'M', 'M', 'M'),
             ExamenYear    = c('2007','2007','2007','2008','2008','2008','2008','2009','2009','2009'),
             Exam          = c('algebra', 'stats', 'bio', 'algebra', 'algebra', 'stats', 'stats', 'algebra', 'bio', 'bio'),
             participated  = c('no','yes','yes','yes','no','yes','yes','yes','yes','yes'),  
             passed      = c('no','yes','yes','yes','no','yes','yes','yes','no','yes'),
             stringsAsFactors = FALSE)

我想创建一个表格,显示每年,所有学生(所有)和女性,参与者和通过者的数量。请注意&#34;其中&#34;以下是指所有学生。

我想到的一张桌子看起来像这样:

cbind(All = table(d1$ExamenYear),
  participated      = table(d1$ExamenYear, d1$participated)[,2],
  ofwhichFemale     = table(d1$ExamenYear, d1$StudentGender)[,1],
  ofwhichpassed     = table(d1$ExamenYear, d1$passed)[,2])

我相信在R.中有更好的方法来处理这类事情。

注意:我已经看过LaTex解决方案,但我没有使用这对我有用,因为我需要在Excel中导出表格。

提前致谢

4 个答案:

答案 0 :(得分:9)

使用plyr

require(plyr)
ddply(d1, .(ExamenYear), summarize,
      All=length(ExamenYear),
      participated=sum(participated=="yes"),
      ofwhichFemale=sum(StudentGender=="F"),
      ofWhichPassed=sum(passed=="yes"))

给出了:

  ExamenYear All participated ofwhichFemale ofWhichPassed
1       2007   3            2             2             2
2       2008   4            3             2             3
3       2009   3            3             0             2

答案 1 :(得分:4)

plyr包非常适合此类事情。首先加载包

library(plyr)

然后我们使用ddply函数:

ddply(d1, "ExamenYear", summarise, 
      All = length(passed),##We can use any column for this statistics
      participated = sum(participated=="yes"),
      ofwhichFemale = sum(StudentGender=="F"),
      ofwhichpassed = sum(passed=="yes"))

基本上,ddply期望数据帧作为输入并返回数据帧。然后,我们将输入数据框分开ExamenYear。在每个子表上,我们计算一些汇总统计信息。请注意,在ddply中,我们在引用列时不必使用$表示法。

答案 2 :(得分:4)

可能有一些修改(使用with减少df$调用的数量并使用字符索引来改进自我文档)到您的代码,这将使它更容易阅读并且是ddply解决方案的有力竞争对手:

with( d1, cbind(All = table(ExamenYear),
  participated      = table(ExamenYear, participated)[,"yes"],
  ofwhichFemale     = table(ExamenYear, StudentGender)[,"F"],
  ofwhichpassed     = table(ExamenYear, passed)[,"yes"])
     )

     All participated ofwhichFemale ofwhichpassed
2007   3            2             2             2
2008   4            3             2             3
2009   3            3             0             2

我希望这比ddply解决方案快得多,尽管只有在处理更大的数据集时才会出现这种情况。

答案 3 :(得分:1)

您可能还想了解一下plyr的下一个迭代器:dplyr

它使用类似ggplot的语法,并通过在C ++中编写关键部分来提供快速性能。

d1 %.% 
group_by(ExamenYear) %.%    
summarise(ALL=length(ExamenYear),
          participated=sum(participated=="yes"),
          ofwhichFemale=sum(StudentGender=="F"),
          ofWhichPassed=sum(passed=="yes"))