2

假设我有一个不错的小数据框

df <- data.frame(x=seq(1,5),y=seq(5,1),z=c(1,2,3,2,1),a=c(1,1,1,2,2))
df
##  x y z a
## 1 1 5 1 1
## 2 2 4 2 1
## 3 3 3 3 1
## 4 4 2 2 2
## 5 5 1 1 2

我想要aggregate其中的一部分:

aggregate(cbind(x,z)~a,FUN=sum,data=df)
##  a x z
## 1 1 6 6
## 2 2 9 3

我如何使它成为程序化的?我想通过:

  1. 要聚合的变量列表cbind(x,z)
  2. 分组变量a(我将在程序的其他几个部分中使用它,所以传递整个东西cbind(x,z)~a没有帮助)
  3. 事情发生的环境

我的出发点是

blah <- function(varlist,groupvar,df) {
# I kinda like to see what I am doing here 
cat(paste0(deparse(substitute(varlist)),"~",deparse(substitute(groupvar))),"\n")
cat(is.data.frame(df),"\n")
cat(dim(df),"\n")
# but I really need to aggregate this
return( aggregate(eval(deparse(substitute(varlist))~deparse(substitute(groupvar)),df),
FUN=sum,data=df) )
}

它工作到一半:

blah(cbind(x,z),a,df)
## [1] "cbind(x, z)~a"
## TRUE 
## 5 4
## Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument 

所以我有点能够建立我需要的公式的字符表示,但将它放入aggregate()失败。

4

0 回答 0