【问题标题】:How to run lm for each subset of the data frame, and then aggreage the result? [duplicate]如何为数据帧的每个子集运行 lm,然后聚合结果? [复制]
【发布时间】:2013-05-14 02:10:05
【问题描述】:

我有一个大数据框 df,列名为:

age, income, country

其实我想做的很简单,做

fitFunc<-function(thisCountry){
    subframe<-df[which(country==thisCountry)];
    fit<-lm(income~0+age, data=subframe);
    return(coef(fit));
}

针对每个国家。然后将结果聚合到一个新的数据框中,如下所示:

    countryname,  coeffname
1      USA         1.2
2      GB          1.0
3      France      1.1

我尝试过:

do.call("rbind", lapply(allRics[1:5], fitit))

但我不知道下一步该做什么。

谁能帮忙?

谢谢!

【问题讨论】:

  • 我不知道这个...显然lm 有一个subset 选项:stackoverflow.com/questions/11328003/… 看看右边的其他“相关链接”。
  • 还有什么问题?小提示 - 在subframe&lt;-df[which(country==thisCountry),] 中添加逗号,否则此行应返回错误。

标签: r lm


【解决方案1】:

请注意,plyr 包是为此类任务创建的。它对数据的子集执行函数并以指定的形式返回结果。使用ddply,我们输入一个数据框并获得一个带有结果的数据框。请参阅plyr 示例会话和帮助文件以了解更多信息。熟悉这个包是非常值得的! 请参阅http://plyr.had.co.nz/ 了解一下。

library(plyr)
age <- runif(1000, 18, 80)
income <- 2000 + age*100 + rnorm(1000,0, 2000)
country <- factor(sample(LETTERS[1:10], 1000, replace = T))
dat <- data.frame(age, income, country)

get.coef <- function(dat) lm(income ~ 0 + age, dat)$coefficients

ddply(dat, .(country), get.coef)

【讨论】:

    【解决方案2】:

    使用@user20650 的示例数据,这似乎产生了相同的结果:

    require(data.table)
    dt <- data.table(df)
    dt[,list(age=lm(income~0+age)$coef),by=country]
    
    #    country      age
    # 1:      gb 2.428830
    # 2:      us 2.540879
    # 3:  france 2.369560
    

    您需要先安装data.table 软件包。

    【讨论】:

      【解决方案3】:

      这对你有用吗?

          set.seed(1)
          df<-data.frame(income=rnorm(100,100,20),age=rnorm(100,40,10),country=factor(sample(1:3,100,replace=T),levels=1:3,labels=c("us","gb","france")))
      
          out<-lapply(levels(df$country) , function(z) {
              data.frame(country=z, age= coef(lm(income~0+age, data=df[df$country==z,])),row.names=NULL)
          })
      do.call(rbind ,out)
      

      【讨论】:

      • 感谢您的帮助!但这只会给出一个单列数据框,对吗?如何将国家列与输出绑定?你知道吗?
      • 编辑答案以包括国家/地区
      • 嗨 20650,这太棒了!非常感谢!
      猜你喜欢
      • 2020-02-04
      • 2019-05-24
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      相关资源
      最近更新 更多