【问题标题】:How to use weighted gini function within aggregate function?如何在聚合函数中使用加权基尼函数?
【发布时间】:2015-02-28 16:25:51
【问题描述】:

我正在尝试使用数据中不同组的样本权重计算基尼系数。我更喜欢使用aggregate,因为我后来使用aggregate 的输出来绘制系数。我找到了替代方法,但在这些情况下,输出并不完全符合我的需要。

library(reldist) #to get gini function
dat <- data.frame(country=rep(LETTERS, each=10)[1:50], replicate(3, sample(11, 10)), year=sample(c(1990:1994), 50, TRUE),wght=sample(c(1:5), 50, TRUE))
dat[51,] <- c(NA,11,2,6,1992,3) #add one more row with NA for country

gini(dat$X1) #usual gini for all
gini(dat$X1,weight=dat$wght) #gini with weight, that's what I actually need
print(a1<-aggregate( X1 ~ country+year, data=dat, FUN=gini)) 
#Works perfectly fine without weight. 

但是,现在如何在聚合中指定权重选项?我知道还有其他方法(as shown here):

print(b1<-by(dat,list(dat$country,dat$year), function(x)with(x,gini(x$X1,x$wght)))[]) 
#By function works with weight but now the output has NAs in it

print(s1<-sapply(split(dat, dat$country), function(x) gini(x$X1, x$wght))) 
#This seems to a good alternative but I couldn't find a way to split it by two variables

library(plyr)
print(p1<-ddply(dat,.(country,year),summarise, value=gini(X1,wght))) 
#yet another alternative but now the output includes NAs for the missing country

如果有人能告诉我在aggregate 中使用加权gini 函数的方法,那将非常有帮助,因为它完全按照我需要的方式产生输出。否则,我想我会使用其中一种替代方案。

【问题讨论】:

  • addNA 中的rbind 是什么?
  • @Metrics 我的意思是添加一个额外的行,以便为国家变量添加一个 NA 的案例。我一定是删掉了中间的那条线。我现在更正了。谢谢!
  • 请使用data.table和dplyr查看答案。
  • @Metrics OP 明确要求 aggregate 解决方案。
  • @Khashaa:我已经添加了。

标签: r function aggregate


【解决方案1】:
 #using aggregate
    aggregate( X1 ~ country+year, data=dat, FUN=gini,weights=dat$wght) # gives different answer than the data.table and dplyr (not sure why?)
 #using data.table
    library(data.table)
    DT<-data.table(dat)
    DT[,list(mygini=gini(X1,wght)),by=.(country,year)]

 #Using dplyr
    library(dplyr)
    dat %>%
    group_by(country,year)%>%
    summarise(mygini=gini(X1,wght))

【讨论】:

  • 我无法使用 dplyr 运行您的代码。带有 data.table 的那个工作正常,但输出包括国家变量存在 NA 的观察结果。
  • 是的,对于有 NA 的国家/地区,它包括 NA。如果不需要,您必须删除这些 NA。您必须为dplyr 执行library(dplyr)
  • 谢谢,但这正是我要求提供聚合解决方案的原因(如果可能的话!)。否则 ddply 无论如何也会给出相同的输出。是的,我的错!我认为必要的包是 plyr。
  • 刚刚看到添加。这正是我需要的,非常感谢!这么简单的事情!我应该想到...
  • 好的,谢谢!我从答案中删除了aggregate 评论,因为它给出了一个误导性的解决方案。别介意另一个问题,这是一个格式化的事情。我试图找到一种将聚合写为aggregate 的方法。我找到了!
猜你喜欢
  • 2016-11-04
  • 2014-01-04
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
相关资源
最近更新 更多