如何为数据帧的每个子集运行lm,然后汇总结果? [英] How to run lm for each subset of the data frame, and then aggreage the result?
本文介绍了如何为数据帧的每个子集运行lm,然后汇总结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大数据框df,其列名为:
I have a big data frame df, with columns named as :
age, income, country
我想做的实际上很简单,要做
what I want to do is very simpe actually, do
fitFunc<-function(thisCountry){
subframe<-df[which(country==thisCountry)];
fit<-lm(income~0+age, data=subframe);
return(coef(fit));
}
每个国家/地区.然后将结果汇总到一个新的数据框中,如下所示:
for each individual country. Then aggregate the result into a new data frame looks like :
countryname, coeffname
1 USA 1.2
2 GB 1.0
3 France 1.1
我试图做:
do.call("rbind", lapply(allRics[1:5], fitit))
但是我不知道下一步该怎么做.
but i don know what to do next.
任何人都可以帮忙吗?
谢谢!
推荐答案
这对您有用吗?
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)
这篇关于如何为数据帧的每个子集运行lm,然后汇总结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文