2012-08-09 107 views
1

我刚刚发现了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))), 
    ) 

感谢

+0

为什么不直接编写自己的函数,而是使用'summarise'? – joran 2012-08-09 18:18:48

+0

谢谢乔兰。事实是:我不知道这个功能如何看起来像。我尝试了几个想法来使用表函数无济于事。仅供参考:我使用的数据有几个因素。 – user1043144 2012-08-09 18:32:10

回答

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当做福音。我只是把它写在我头顶。当然可以进行改进/修改,但至少可以从头开始。

2

感谢乔兰。 我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:我还是不明白什么(组)代表,但