在 R 中插入整齐的数据
Interpolate tidy data in R
我有以下年份的人口数据:1966 年、1971 年、1976 年。我想创建另一个整洁的数据框,其中包含缺失的年份(即 1967 年、1968 年、1969 年、1970 年、1972 年、1973 年、1974 年、1975 年) ).线性插值即可。
我认为涉及 approx
或 approxfun
,但我不确定如何。
library("tidyverse")
df <- tibble(
year = c(1976, 1971, 1966, 1976, 1971, 1966, 1976, 1971, 1966),
age_min = c(rep(0, 3), rep(5, 3), rep(10, 3)),
population = c(180, 200, 300, 150, 250, 450, 25, 50, 150)
)
p1971 <- filter(df, year == 1971)
p1976 <- filter(df, year == 1976)
ggplot(data = p1971, aes(x = age_min, y = population)) +
# 1971 population distribution
geom_point(size = 4, color = "red") +
geom_line(color = "red", size = 1.5) +
geom_text(label = year, nudge_y = 9) +
# 1976 population distribution
geom_point(data = p1976, aes(x = age_min, y = population), size = 3, color = "blue") +
geom_line(data = p1976, aes(x = age_min, y = population), color = "blue", size = 1.5) +
geom_text(data = p1976, aes(x = age_min, y = population), label = p1976$year, nudge_y = -9)
根据?na.approx
(来自zoo
)
Missing values (NAs) are replaced by linear interpolation via approx or cubic spline interpolation via spline, respectivel
因此,我们可以在使用 complete
创建缺失的 'year' 之后使用 na.approx
library(dplyr)
library(tidyr)
library(zoo)
df %>%
complete(age_min, year = 1966:1976) %>%
group_by(age_min) %>%
mutate(population =na.approx(population, na.rm = FALSE))
我有以下年份的人口数据:1966 年、1971 年、1976 年。我想创建另一个整洁的数据框,其中包含缺失的年份(即 1967 年、1968 年、1969 年、1970 年、1972 年、1973 年、1974 年、1975 年) ).线性插值即可。
我认为涉及 approx
或 approxfun
,但我不确定如何。
library("tidyverse")
df <- tibble(
year = c(1976, 1971, 1966, 1976, 1971, 1966, 1976, 1971, 1966),
age_min = c(rep(0, 3), rep(5, 3), rep(10, 3)),
population = c(180, 200, 300, 150, 250, 450, 25, 50, 150)
)
p1971 <- filter(df, year == 1971)
p1976 <- filter(df, year == 1976)
ggplot(data = p1971, aes(x = age_min, y = population)) +
# 1971 population distribution
geom_point(size = 4, color = "red") +
geom_line(color = "red", size = 1.5) +
geom_text(label = year, nudge_y = 9) +
# 1976 population distribution
geom_point(data = p1976, aes(x = age_min, y = population), size = 3, color = "blue") +
geom_line(data = p1976, aes(x = age_min, y = population), color = "blue", size = 1.5) +
geom_text(data = p1976, aes(x = age_min, y = population), label = p1976$year, nudge_y = -9)
根据?na.approx
(来自zoo
)
Missing values (NAs) are replaced by linear interpolation via approx or cubic spline interpolation via spline, respectivel
因此,我们可以在使用 complete
na.approx
library(dplyr)
library(tidyr)
library(zoo)
df %>%
complete(age_min, year = 1966:1976) %>%
group_by(age_min) %>%
mutate(population =na.approx(population, na.rm = FALSE))