如何对数据帧的每个子集运行lm,然后对结果进行聚合



我有一个大数据框架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

I tried to do:

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

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

有人能帮忙吗?

谢谢!

这对你有用吗?

    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)

使用@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包。

注意,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)

相关内容

最新更新