【问题标题】:error in user defined function which generate statistics by group按组生成统计信息的用户定义函数中的错误
【发布时间】:2016-02-04 11:11:12
【问题描述】:

我正在尝试创建按组返回统计信息的功能,如下所示。 为了按组进行统计,我在这个函数代码中使用了子集。 但是当参数“y”应用于“子集”时发生错误。 我怎么解决这个问题?我会等待你的智慧。 肯定可以使用tapply,但我的意图是发挥作用。 谢谢。

sbyg<-function(dt,grp,y) {
# dt=data.frame, grp=group variable, y=value variable
ng<-length(unique(grp))
x<-as.vector(unique(grp))
statis<-matrix(nrow=ng,ncol=6)
for (i in 1:ng) {
  dta<-dt[grp==x[i],]
  attach(dta)
  statis[i,1]<-nrow(dta) # 건수
  statis[i,2]<-colSums(!is.na(dta))[1] # nonmiss건수
  statis[i,3]<-mean(dta[,y],na.rm=TRUE) # 평균
  statis[i,4]<-median(dta[,y],na.rm=TRUE) # 중위수
  statis[i,5]<-min(dta[,y],na.rm=TRUE)
  statis[i,6]<-max(dta[,y],na.rm=TRUE)
  detach(dta)
}
rownames(statis)<-x
colnames(statis)<-c("count","nonmiss","mean","median","min","max")
statis
}

sbyg(iris,Species,Sepal.Length)  # error occurs

【问题讨论】:

  • 您可以使用 group by 函数之一来执行此操作,例如 aggregatedata.tableddplyr
  • 同上here

标签: r function arguments subset


【解决方案1】:

你的函数调用应该是这样的:

sbyg(iris,"Species","Sepal.Length")

除非 iris 是 data.table 对象(默认情况下不是)。

编辑:修改功能:

sbyg<-function(dt,grp,y) {
  # dt=iris ; grp="Species"; y="Sepal.Length"
  ng<-length(unique(dt[, grp]))
  x<-as.vector(unique(dt[, grp]))
  statis<-matrix(nrow=ng,ncol=6)
  for (i in 1:ng) { # i <- 1
    dta<-dt[dt[, grp]==x[i],]
    statis[i,1]<-nrow(dta) # 건수
    statis[i,2]<-colSums(!is.na(dta))[1] # nonmiss건수
    statis[i,3]<-mean(dta[,y],na.rm=TRUE) # 평균
    statis[i,4]<-median(dta[,y],na.rm=TRUE) # 중위수
    statis[i,5]<-min(dta[,y],na.rm=TRUE)
    statis[i,6]<-max(dta[,y],na.rm=TRUE)
  }
  rownames(statis)<-x
  colnames(statis)<-c("count","nonmiss","mean","median","min","max")
  statis
}

但这不是一个最优函数。最好的方法是使用tapply

【讨论】:

  • 感谢您的简洁回答,YCR 引号(") 几乎解决了我的问题。但是,'by group' 不起作用。不知道是什么问题。
猜你喜欢
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多