【发布时间】:2021-04-06 12:59:07
【问题描述】:
我缺少一些日期,我想在每个组内插入和推断值,即使我只有一个可用值。
#create an example
library(zoo)
library(tidyverse)
df <- data.frame(a = c("group1","group1","group1","group1","group2","group2","group2","group2","group3","group3"), b = c(1,2,NA,4,1,NA,NA,NA,NA,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 给出错误,我确定我错过了什么......
【问题讨论】: