首页 > 解决方案 > 在 R 中使用 split() 后将观察结果制成表格的惯用方法

问题描述

有没有一种更惯用的方法来制表观察的数量是每个数据帧都是通过在 R 中的两列上拆分数据帧获得的?很难描述,所以我写了我想做的事。

splittable <- function(data,rowdata,coldata) {
        # data is the data frame for all your data
        # rowdata is a column from data
        # coldata is another column from data
        # This function returns a table counting the number of observations
        # from splitting the data by the rowdata and coldata values.
        splits <- as.data.frame(lapply(split(data,list(rowdata,coldata)),nrow))
        rowlevs <- levels(as.factor(rowdata))
        numrowlevs <- length(rowlevs)
        collevs <- levels(as.factor(coldata))
        outtable <- data.frame()
        for (i in seq(from=1,to=numrowlevs,by=1)) {
                indexes <- seq(from=i,to=length(splits),by=numrowlevs)
                tempdf <- as.data.frame(splits[indexes])
                names(tempdf) <- collevs
                outtable <- rbind(outtable,tempdf)
        }
        row.names(outtable) <- rowlevs
        return(outtable)
}

似乎应该有一个功能可以为我执行此操作,但我找不到它。

标签: r

解决方案


我想你可能只是重新发明了这个功能table。让我们检查一下mtcars

splittable(mtcars, mtcars$gear, mtcars$carb)
#>   1 2 3 4 6 8
#> 3 3 4 3 5 0 0
#> 4 4 4 0 4 0 0
#> 5 0 2 0 1 1 1

table(mtcars$gear, mtcars$carb)
#>    
#>     1 2 3 4 6 8
#>   3 3 4 3 5 0 0
#>   4 4 4 0 4 0 0
#>   5 0 2 0 1 1 1

推荐阅读