Trying to fit multiple logistic models to data for different counties and would like it all together in one data frame at the end (all counties, all predicted populations, for specified years).
Here's the data:
county <- structure(list(name = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
5L, 5L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L,
8L, 9L, 9L, 9L, 9L, 9L), .Label = c("Alachua", "Columbia", "Gilchrist",
"Lake", "Levy", "Marion", "Orange", "Seminole", "Volusia"), class =
"factor"),
year = c(1920L, 1940L, 1970L, 1990L, 2010L, 1920L, 1940L,
1970L, 1990L, 2010L, 1920L, 1940L, 1970L, 1990L, 2010L, 1920L,
1940L, 1970L, 1990L, 2010L, 1920L, 1940L, 1970L, 1990L, 2010L,
1920L, 1940L, 1970L, 1990L, 2010L, 1920L, 1940L, 1970L, 1990L,
2010L, 1920L, 1940L, 1970L, 1990L, 2010L, 1920L, 1940L, 1970L,
1990L, 2010L), pop = c(24662.84498, 38518.67335, 105080.0739,
182378.0527, 247964.4355, 14353.67655, 16988.63031, 25423.53768,
42636.12851, 67396.52047, 6955.297482, 4331.7027, 3661.621676,
9835.709676, 16780.95117, 12812.1731, 27202.15681, 65668.28125,
153585.2153, 297441.8053, 10034.20186, 12707.52359, 12911.58508,
26370.47373, 41650.51535, 23990.09377, 31340.67059, 69056.41468,
194358.0547, 334117.7792, 19825.73528, 68559.76913, 337259.2307,
670422.46, 1140314.083, 11027.52715, 23881.62063, 91628.11201,
298115.877, 438079.7446, 24526.72497, 55775.68449, 175004.8787,
382885.1367, 516049.0225)), .Names = c("name", "year", "pop"
), row.names = c(NA, -45L), class = "data.frame")
and here's what I've ended up with:
library(dplyr)
county %>%
group_by(name) %>%
(function(x) {
fm<- nls(pop ~ SSlogis(year, phi1, phi2, phi3), data = x)
timevalues <- c(1992, 2002, 2007, 2012)
predict <- predict(fm,list(year=timevalues))
cbind(predict, predict)
})
but this only gives me a list of four data points:
out:
predict predict
[1,] 226713.5 226713.5
[2,] 293596.4 293596.4
[3,] 326455.5 326455.5
[4,] 357640.8 357640.8
with no clue as to what county they are for? If I use this code separately (without using groupby), I can get it to work. But then I have to do it separately for each county and then bind it all myself, which is going to get tedious once I'm working with more than 9 counties.