我正在尝试按 Year 和 CountyID 对数据进行分组,然后在子集数据上使用 splinefun(三次样条插值)。我对想法持开放态度,但是 splinefun 是必须的,不能改变。
这是我尝试使用的代码:
age <- seq(from = 0, by = 5, length.out = 18)
TOT_POP <- df %.%
group_by(unique(df$Year), unique(df$CountyID) %.%
splinefun(age, c(0, cumsum(df$TOT_POP)), method = "hyman")
这是我的数据示例 Year = 2010 : 2013, Agegrp = 1 : 17 和 CountyIDs 等于美国的所有县。
CountyID Year Agegrp TOT_POP
1001 2010 1 3586
1001 2010 2 3952
1001 2010 3 4282
1001 2010 4 4136
1001 2010 5 3154
我正在做的是采用 Agegrp 1 : 17 并将分组分成 0-84 年。现在每个组代表 5 年。splinefun 允许我这样做,同时为该过程提供一定程度的数学严谨性,即 splinefun 允许我提供美国每个县的每个年龄的人口总数。
最后,splinefun 代码本身确实可以工作,但在 group_by 函数中却没有,它会产生:
Error: wrong result size(4), expected 68 or 1.
我使用的 splinefun 代码是这样工作的
TOT_POP <- splinefun(age, c(0, cumsum(df$TOT_POP)),
method = "hyman")
TOT_POP = pmax(0, diff(TOT_POP(c(0:85))))
在一年内对一个 CountyID 进行了测试。我需要在“x”年和大约 3200 个县迭代这个过程。