将频率和汇总统计结合在一个表中?

时间:2012-08-09 17:44:53

标签: r plyr

我刚刚发现了plyr的力量frequency table with several variables in R 我仍在努力了解它是如何工作的,我希望有些人可以帮助我。

我想创建一个表(数据框),我可以在其中组合频率和摘要统计数据,但不对值进行硬编码。

这是一个示例数据集

require(datasets)

d1 <- sleep
# I classify the variable extra to calculate the frequencies 
extraClassified <- cut(d1$extra, breaks = 3, labels = c('low', 'medium', 'high') )
d1 <- data.frame(d1, extraClassified)

我正在寻找的结果应该是这样的:

  require(plyr)

  ddply(d1, "group", summarise,  
  All = length(ID), 

  nLow    = sum(extraClassified  == "low"),
  nMedium = sum(extraClassified  == "medium"),      
  nHigh =  sum(extraClassified  == "high"),

  PctLow     = round(sum(extraClassified  == "low")/ length(ID), digits = 1),
  PctMedium  = round(sum(extraClassified  == "medium")/ length(ID), digits = 1),      
  PctHigh    = round(sum(extraClassified  == "high")/ length(ID), digits = 1),

  xmean    = round(mean(extra), digits = 1),
  xsd    =   round(sd(extra), digits = 1))

我的问题:如何在不对值进行硬编码的情况下执行此操作?

记录: 我尝试了这段代码,但它不起作用

ddply (d1, "group", 
   function(i) c(table(i$extraClassified),     
   prop.table(as.character(i$extraClassified))),
   )

提前致谢

2 个答案:

答案 0 :(得分:2)

这是一个让你入门的例子:

foo <- function(x,colfac,colval){
    tbl <- table(x[,colfac])
    res <- cbind(n = nrow(x),t(tbl),t(prop.table(tbl)))
    colnames(res)[5:7] <- paste(colnames(res)[5:7],"Pct",sep = "")
    res <- as.data.frame(res)
    res$mn <- mean(x[,colval])
    res$sd <- sd(x[,colval])
    res
}

ddply(d1,.(group),foo,colfac = "extraClassified",colval = "extra")

不要把那个函数foo中的任何东西当作福音。我只是写下了我的头脑。当然可以进行改进/修改,但至少这是开始的事情。

答案 1 :(得分:2)

感谢Joran。 我slighlty修改了你的函数,使其更通用(不参考变量的位置)。

require(plyr)
            foo <- function(x,colfac,colval)
            {

              # table with frequencies
              tbl    <- table(x[,colfac])
              # table with percentages 
              tblpct <- t(prop.table(tbl))
              colnames( tblpct) <- paste(colnames(t(tbl)), 'Pct', sep = '')

              # put the first part together 
              res <- cbind(n = nrow(x), t(tbl), tblpct)
              res <- as.data.frame(res)

              # add summary statistics 

              res$mn <- mean(x[,colval])
              res$sd <- sd(x[,colval])
              res
            }

ddply(d1,.(group),foo,colfac = "extraClassified",colval = "extra")

它有效!

P.S:我仍然不明白(小组)代表什么,但