Applying multiple functions to each column in a data frame using aggregate

筅森魡賤 提交于 2019-12-22 10:34:00

问题


When I need to apply multiple functions to multiple columns sequentially and aggregate by multiple columns and want the results to be bound into a data frame I usually use aggregate() in the following manner:

# bogus functions
foo1 <- function(x){mean(x)*var(x)}
foo2 <- function(x){mean(x)/var(x)}

# for illustration purposes only
npk$block <- as.numeric(npk$block) 

subdf <- aggregate(npk[,c("yield", "block")],
                   by = list(N = npk$N, P = npk$P),
                   FUN = function(x){c(col1 = foo1(x), col2 = foo2(x))})

Having the results in a nicely ordered data frame is achieved by using:

df <- do.call(data.frame, subdf)

Can I avoid the call to do.call() by somehow using aggregate() smarter in this scenario or shorten the whole process by using another base R solution from the start?


回答1:


As @akrun suggested, dplyr's summarise_each is well-suited to the task.

library(dplyr)
npk %>% 
  group_by(N, P) %>%
  summarise_each(funs(foo1, foo2), yield, block)

# Source: local data frame [4 x 6]
# Groups: N
# 
#   N P yield_foo2 block_foo2 yield_foo1 block_foo1
# 1 0 0   2.432390          1   1099.583      12.25
# 2 0 1   1.245831          1   2205.361      12.25
# 3 1 0   1.399998          1   2504.727      12.25
# 4 1 1   2.172399          1   1451.309      12.25



回答2:


You can use

df=data.frame(as.list(aggregate(...


来源:https://stackoverflow.com/questions/26624587/applying-multiple-functions-to-each-column-in-a-data-frame-using-aggregate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!