使用tapply按组分组多个列

Mar*_*ler 13 r tapply

我想按组分列各个列,我的第一个想法是使用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)
Run Code Online (Sandbox Code Playgroud)

这不起作用:

tapply(df.1, df.1$state, function(x) {colSums(x[,3:5])})
Run Code Online (Sandbox Code Playgroud)

帮助页面说:

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

X       an atomic object, typically a vector.
Run Code Online (Sandbox Code Playgroud)

我对这个typically a vector让我不知道是否可以使用数据框的短语感到困惑.我从来都不清楚用什么atomic object方法.

以下是有效的几种替代方案tapply.第一种选择是结合tapply使用的变通方法apply.

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
Run Code Online (Sandbox Code Playgroud)

这是源代码,tapply除了我更改了行:

nx <- length(X)
Run Code Online (Sandbox Code Playgroud)

至:

nx <- ifelse(is.vector(X), length(X), dim(X)[1])
Run Code Online (Sandbox Code Playgroud)

此修改版本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
Run Code Online (Sandbox Code Playgroud)

EDi*_*EDi 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 
Run Code Online (Sandbox Code Playgroud)


nog*_*pes 6

你在找by.它使用INDEX你假设的方式tapply,按行.

by(df.1, df.1$state, function(x) colSums(x[,3:5]))
Run Code Online (Sandbox Code Playgroud)

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