r - How to run lm for each subset of the data frame, and then aggreage the result? -


this question has answer here:

i have big data frame df, columns named :

age, income, country 

what want 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. aggregate result new data frame looks :

    countryname,  coeffname 1      usa         1.2 2      gb          1.0 3      france      1.1 

i tried :

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

but don know next.

can help?

thanks!

does work you?

    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) 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -