我有一个大数据框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))
但我不知道下一步该做什么。
有人可以帮忙吗?
谢谢!
答案 0 :(得分:2)
这对你有用吗?
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)
答案 1 :(得分: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
软件包。
答案 2 :(得分: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)