14

我想按组汇总各个列,我的第一个想法是使用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
4

3 回答 3

16

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 
于 2013-07-27T23:18:36.523 回答
6

你正在寻找by. 它以INDEX您假设的方式tapply逐行使用。

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

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

于 2013-07-27T23:20:04.030 回答
-1

by正如 EDi 建议的那样,我查看了 的源代码。该代码比我对tapply. 我现在发现它my.tapply不适用于下面的更复杂的场景,其中applescherriesstateand求和county。如果我开始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)})
于 2013-07-28T08:13:53.290 回答