R dplyr 对具有不同最小值和最大值的每个组执行插值

R dplyr perform interpolation for each group with varying min and max

每个段有不同的range,例如A是从1到3,而C是从1到7。 对于每个片段,可能缺少我想要执行插值的时间(线性、样条等)

如何在 dplyr 中完成?

have <- data.frame(time   =c(1,3,1,2,5,1,3,5,7),
                 segment=c('A','A','B','B','B','C','C','C','C'),
                 toInterpolate= c(0.12,0.31,0.15,0.24,0.55,0.11,0.35,0.53,0.79))
have


want <- data.frame(time   =c(1,2,3,1,2,3,4,5,1,2,3,4,5,6,7),
                   segment=c('A','A','A','B','B','B','B','B','C','C','C','C','C','C','C'),
                   Interpolated= c(0.12,0.21,0.31,0.15,0.24,0.34,0.41,0.55,0.11,0.28,0.35,0.45,0.53,0.69,0.79))
# note that the interpolated values here are just randomnly put, (not based on actual linear/spline interpolation)

want

我们可以使用 complete 完成序列,并使用 na.splinezoo 进行插值。

library(dplyr)
library(tidyr)
library(zoo)

have %>%
  group_by(segment) %>%
  complete(time = min(time):max(time)) %>%
  mutate(toInterpolate = na.spline(toInterpolate))

#  segment  time toInterpolate
#   <chr>   <dbl>         <dbl>
# 1 A           1         0.12 
# 2 A           2         0.215
# 3 A           3         0.31 
# 4 B           1         0.15 
# 5 B           2         0.24 
# 6 B           3         0.337
# 7 B           4         0.44 
# 8 B           5         0.55 
# 9 C           1         0.11 
#10 C           2         0.246
#11 C           3         0.35 
#12 C           4         0.439
#13 C           5         0.53 
#14 C           6         0.641
#15 C           7         0.79 

为更小的粒度创建序列。

have %>%
  group_by(segment) %>%
  complete(time = min(time):max(time)) %>%
  mutate(toInterpolate = na.spline(toInterpolate)) %>%
  complete(time = seq(min(time), max(time), 0.1))