I have a data.frame of data from the World Bank which looks something like this;
country date BirthRate US.
4 Aruba 2011 10.584 25354.8
5 Aruba 2010 10.804 24289.1
6 Aruba 2009 11.060 24639.9
7 Aruba 2008 11.346 27549.3
8 Aruba 2007 11.653 25921.3
9 Aruba 2006 11.977 24015.4
All in all there 70 something sub sets of countries in this data frame that I would like to run a linear regression on.
If I use the following I get a nice lm for a single country;
andora = subset(high.sub, country == "Andorra")
andora.lm = lm(BirthRate~US., data = andora)
anova(andora.lm)
summary(andora.lm)
But when I try to use the same type of code in a for loop I an error which I'll print below the code;
high.sub = subset(highInc, date > 1999 & date < 2012)
high.sub <- na.omit(high.sub)
highnames <- unique(high.sub$country)
for (i in highnames) {
linmod <- lm(BirthRate~US., data = high.sub, subset = (country == "[i]"))
}
Error message:
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
0 (non-NA) cases
If I can get this loop to run I would ideally like to append the coefficients and even better the r-squared values for each model to an empty data.frame. Any help would be greatly appreciated.
Thanks
Josh
i
. R is not a macro language. Plus you need to stop overwriting values in loops. Either use lapply to return values in a list or learn to index list elements. – IRTFMmods <- lapply( highnames, function(nm) lm(BirthRate~US., data = high.sub, subset = (country == nm)) ); mods[["Andorra"]]
– IRTFMlmList
fromnlme
would work for you. – Roman Luštrik