使用 na.spline() 和 case_when()

问题描述

我缺少一些日期,即使我只有一个可用值,我也想在每个组内插入和外推值。

#create an example
library(zoo)
library(tidyverse)

df <- data.frame(a = c("group1","group1","group2","group3","group3"),b = c(1,2,NA,4,1,NA))
        a  b
1  group1  1
2  group1  2
3  group1 NA
4  group1  4
5  group2  1
6  group2 NA
7  group2 NA
8  group2 NA
9  group3 NA
10 group3 NA

我想得到这个:

        a  b b_interpolated
1  group1  1              1
2  group1  2              2
3  group1 NA              3
4  group1  4              4
5  group2  1              1
6  group2 NA              1
7  group2 NA              1
8  group2 NA              1
9  group3 NA             NA
10 group3 NA             NA

首先,我尝试按组使用 na.spline

df %>% group_by(a) %>% mutate(b_interpolated = na.spline(b,na.rm = FALSE))

并给我这个错误:

Error: Problem with `mutate()` input `test`.
x zero non-NA points
ℹ Input `test` is `na.spline(b,na.rm = FALSE)`.
ℹ The error occurred in group 3: a = "group3".

所以我尝试在任何值可用时使用 na.spline

#Interpolate and extrapolate test
test <- df %>% group_by(a) %>% mutate(test = case_when(all(is.na(b)) == TRUE ~ "empty",all(is.na(b)) == FALSE ~ "ok"))

这似乎可行,但如果我尝试使用 na.spline:

test2 <- df %>% group_by(a) %>% mutate(b_interpolated = case_when(all(is.na(b)) == TRUE ~ b,all(is.na(b)) == FALSE ~ na.spline(b,na.rm = FALSE)))

然后,我又犯了另一个错误:

Error: Problem with `mutate()` input `b_interpolated`.
x zero non-NA points
ℹ Input `b_interpolated` is `case_when(...)`.
ℹ The error occurred in group 3: a = "group3"

如果我使用 na.approx,则无法推断 group2,因为只有一个值

df %>% group_by(a) %>% mutate(b_interpolated = na.approx(b,na.rm = FALSE,rule = 2))
   a          b b_interpolated
   <chr>  <dbl>          <dbl>
 1 group1     1              1
 2 group1     2              2
 3 group1    NA              3
 4 group1     4              4
 5 group2     1              1
 6 group2    NA             NA
 7 group2    NA             NA
 8 group2    NA             NA
 9 group3    NA             NA
10 group3    NA             NA

我不明白为什么使用 case_when 会出错,我确定我遗漏了一些东西...

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)