【问题标题】:sum multiple columns by group with tapply使用 tapply 按组对多列求和
【发布时间】:2013-07-27 22:45:47
【问题描述】:

我想按组对各个列求和,我的第一个想法是使用tapply。 但是,我无法让tapply 工作。 tapply 可以用来对多列求和吗? 如果没有,为什么不呢?

我在互联网上进行了广泛的搜索,发现了许多类似的问题 早在 2008 年。但是,这些问题都没有得到直接回答。 相反,响应总是建议使用不同的函数。

下面是一个示例数据集,我希望按州对苹果进行汇总,按州对樱桃进行汇总 和各州的李子。在此之下,我编译了许多 tapply 的替代方案 干活。

在底部我展示了对tapply 源代码的简单修改,它允许 tapply 执行所需的操作。

尽管如此,也许我忽略了一种执行所需操作的简单方法 与tapply。我不是在寻找替代功能,但欢迎使用其他替代功能。

鉴于我对tapply 源代码的修改很简单,我想知道为什么会这样,或者 类似的东西,还没有实现。

感谢您的任何建议。如果我的问题是重复的,我很乐意发布我的 问题作为另一个问题的答案。

这是示例数据集:

df.1 <- read.table(text = '

    state   county   apples   cherries   plums
       AA        1        1          2       3
       AA        2       10         20      30
       AA        3      100        200     300
       BB        7       -1         -2      -3
       BB        8      -10        -20     -30
       BB        9     -100       -200    -300

', header = TRUE, stringsAsFactors = FALSE)

这不起作用:

tapply(df.1, df.1$state, function(x) {colSums(x[,3:5])})

帮助页面说:

tapply(X, INDEX, FUN = NULL, ..., simplify = TRUE)

X       an atomic object, typically a vector.

我被typically a vector这个短语弄糊涂了,这让我想知道是否 可以使用数据框。我一直不清楚atomic object 是什么意思。

这里有几个可以替代tapply 的方法。第一种选择是将tapplyapply 结合起来的变通方法。

apply(df.1[,c(3:5)], 2, function(x) tapply(x, df.1$state, sum))

#    apples cherries plums
# AA    111      222   333
# BB   -111     -222  -333

with(df.1, aggregate(df.1[,3:5], data.frame(state), sum))

#   state apples cherries plums
# 1    AA    111      222   333
# 2    BB   -111     -222  -333

t(sapply(split(df.1[,3:5], df.1$state), colSums))

#    apples cherries plums
# AA    111      222   333
# BB   -111     -222  -333

t(sapply(split(df.1[,3:5], df.1$state), function(x) apply(x, 2, sum)))

#    apples cherries plums
# AA    111      222   333
# BB   -111     -222  -333

aggregate(df.1[,3:5], by=list(df.1$state), sum)

#   Group.1 apples cherries plums
# 1      AA    111      222   333
# 2      BB   -111     -222  -333

by(df.1[,3:5], df.1$state, colSums)

# df.1$state: AA
#   apples cherries    plums 
#      111      222      333 
# ------------------------------------------------------------ 
# df.1$state: BB
#   apples cherries    plums 
#     -111     -222     -333

with(df.1, 
     aggregate(x = list(apples   = apples, 
                        cherries = cherries,
                        plums    = plums), 
               by = list(state   = state), 
               FUN = function(x) sum(x)))

#   state apples cherries plums
# 1    AA    111      222   333
# 2    BB   -111     -222  -333

lapply(split(df.1, df.1$state), function(x) {colSums(x[,3:5])} )

# $AA
#   apples cherries    plums 
#      111      222      333 
#
# $BB
#   apples cherries    plums 
#     -111     -222     -333

这里是tapply的源代码,只是我改了行:

nx <- length(X)

到:

nx <- ifelse(is.vector(X), length(X), dim(X)[1])

tapply 的这个修改版本执行所需的操作:

my.tapply <- function (X, INDEX, FUN = NULL, ..., simplify = TRUE)
{
    FUN <- if (!is.null(FUN)) match.fun(FUN)
    if (!is.list(INDEX)) INDEX <- list(INDEX)
    nI <- length(INDEX)
    if (!nI) stop("'INDEX' is of length zero")
    namelist <- vector("list", nI)
    names(namelist) <- names(INDEX)
    extent <- integer(nI)
    nx     <- ifelse(is.vector(X), length(X), dim(X)[1])  # replaces nx <- length(X)
    one <- 1L
    group <- rep.int(one, nx) #- to contain the splitting vector
    ngroup <- one
    for (i in seq_along(INDEX)) {
    index <- as.factor(INDEX[[i]])
    if (length(index) != nx)
        stop("arguments must have same length")
    namelist[[i]] <- levels(index)#- all of them, yes !
    extent[i] <- nlevels(index)
    group <- group + ngroup * (as.integer(index) - one)
    ngroup <- ngroup * nlevels(index)
    }
    if (is.null(FUN)) return(group)
    ans <- lapply(X = split(X, group), FUN = FUN, ...)
    index <- as.integer(names(ans))
    if (simplify && all(unlist(lapply(ans, length)) == 1L)) {
    ansmat <- array(dim = extent, dimnames = namelist)
    ans <- unlist(ans, recursive = FALSE)
    } else {
    ansmat <- array(vector("list", prod(extent)),
            dim = extent, dimnames = namelist)
    }
    if(length(index)) {
        names(ans) <- NULL
        ansmat[index] <- ans
    }
    ansmat
}

my.tapply(df.1$apples, df.1$state, function(x) {sum(x)})

#  AA   BB 
# 111 -111

my.tapply(df.1[,3:4] , df.1$state, function(x) {colSums(x)})

# $AA
#   apples cherries 
#      111      222 
#
# $BB
#   apples cherries 
#     -111     -222

【问题讨论】:

    标签: r tapply


    【解决方案1】:

    tapply 适用于矢量,对于 data.frame,您可以使用 by(它是 tapply 的包装器,查看代码):

    > by(df.1[,c(3:5)], df.1$state, FUN=colSums)
    df.1$state: AA
      apples cherries    plums 
         111      222      333 
    ------------------------------------------------------------------------------------- 
    df.1$state: BB
      apples cherries    plums 
        -111     -222     -333 
    

    【讨论】:

      【解决方案2】:

      您正在寻找by。它使用 INDEX 的方式与您假设 tapply 的方式相同。

      by(df.1, df.1$state, function(x) colSums(x[,3:5]))
      

      您使用tapply 的问题在于您正在按 索引data.frame。 (因为data.frame 实际上只是列的list。)所以,tapply 抱怨您的索引与data.frame 的长度不匹配,即 5。

      【讨论】:

        【解决方案3】:

        按照 EDi 的建议,我查看了 by 的源代码。该代码比我对tapply 中的一行的更改要复杂得多。我现在发现my.tapply 不适用于下面更复杂的场景,其中applescherriesstatecounty 求和。如果我让my.tapply 处理这种情况,我可以稍后在此处发布代码:

        df.2 <- read.table(text = '
        
            state   county   apples   cherries   plums
               AA        1        1          2       3
               AA        1        1          2       3
               AA        2       10         20      30
               AA        2       10         20      30
               AA        3      100        200     300
               AA        3      100        200     300
        
               BB        7       -1         -2      -3
               BB        7       -1         -2      -3
               BB        8      -10        -20     -30
               BB        8      -10        -20     -30
               BB        9     -100       -200    -300
               BB        9     -100       -200    -300
        
        ', header = TRUE, stringsAsFactors = FALSE)
        
        # my function works
        
           tapply(df.2$apples  , list(df.2$state, df.2$county), function(x) {sum(x)})
        my.tapply(df.2$apples  , list(df.2$state, df.2$county), function(x) {sum(x)})
        
        # my function works
        
           tapply(df.2$cherries, list(df.2$state, df.2$county), function(x) {sum(x)})
        my.tapply(df.2$cherries, list(df.2$state, df.2$county), function(x) {sum(x)})
        
        # my function does not work
        
        my.tapply(df.2[,3:4], list(df.2$state, df.2$county), function(x) {colSums(x)})
        

        【讨论】:

          猜你喜欢
          • 2021-02-28
          • 2012-01-03
          • 1970-01-01
          • 2018-10-31
          • 1970-01-01
          • 2021-10-16
          • 1970-01-01
          • 2014-02-05
          相关资源
          最近更新 更多