我有关于居住在弗罗茨瓦夫的人数的数据:
Pop <- data.frame(Year = c(850, 1000, 1200, 1300, 1350, 1318, 1327, 1329),
Pop = c(800, 2250, 5000, 13500, 14000, 13600, 12000, 15950))
有没有办法改变它,每年都是单独的行并且数据被插值?
Pop_long <- data.frame(Year = 850:1329, Pop = 850, ....)
插值将是线性的。我已经做到了,但我敢打赌有更好的方法:
Pop <- Pop
mutate(Year_lead = lead(Year),
Pop_lead = lead(Pop),
Year_diff = Year_lead - Year,
Pop_diff = Pop_lead - Pop,
Pop_add = Pop_diff / Year_diff) %>%
select(Year, Pop, Pop_add)
Pop_long <- data.frame(Year = 850:1329) %>%
merge(Pop, all.x = T)
for(i in 1:nrow(Pop_long)){
if(is.na(Pop_long[i, "Pop"])) {
Pop_long[i, "Pop"] <- Pop_long[i - 1, "Pop_add"] + Pop_long[i - 1, "Pop"]
Pop_long[i, "Pop_add"] <- Pop_long[i - 1, "Pop_add"]
}
}