Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用聚合对数据帧中的每列应用多个函数_R_Aggregate_Split Apply Combine - Fatal编程技术网

R 使用聚合对数据帧中的每列应用多个函数

R 使用聚合对数据帧中的每列应用多个函数,r,aggregate,split-apply-combine,R,Aggregate,Split Apply Combine,当我需要按顺序将多个函数应用于多列并按多列进行聚合,并希望将结果绑定到数据框中时,我通常按以下方式使用aggregate(): # 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 <- aggr

当我需要按顺序将多个函数应用于多列并按多列进行聚合,并希望将结果绑定到数据框中时,我通常按以下方式使用
aggregate()

# 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))})
#伪函数

foo1正如@akrun所建议的那样,
dplyr
的每个
摘要都非常适合这项任务

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
你可以用

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

请注意,在
subdf
中,我还将有一个数据帧。但它将是一个数据帧,在某些列中包含矩阵,这是我非常希望避免的!使用
data.table
(这是该软件包如此流行的几个原因之一),这项任务非常简单。我不认为你能在BaseR中比你展示的方式更容易达到你想要的结果。@lord.garbage我想你不需要
cbind
do.call(data.frame,subdf)
就足够了。另一种选择是使用
dplyr
@akrun,干杯。我将相应地修改这个问题。因为如果有一个更简单的基本
R
解决方案的问题似乎是“否”,我将接受你的回答。
df=data.frame(as.list(aggregate(...