如何解决使用 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 会出错,我确定我遗漏了一些东西...
解决方法
这看起来像是 na.spline 的一个错误。使用它来解决它。
在 na.approx 的情况下,我们使用 na.fill 将数据扩展到开头和结尾的 NA。 na.fill 的第二个参数是一个 3 向量,它给出了左端、内部 NA 和右端的替换规则。它会循环使用,因此我们可以省略右端。
na_spline <- function(x) if (all(is.na(x))) NA else na.spline(x,na.rm = FALSE)
na_approx <- function(x) na.fill(na.approx(x,na.rm = FALSE),c("extend",NA))
df %>%
group_by(a) %>%
mutate(spline = na_spline(b),approx = na_approx(b)) %>%
ungroup
给予:
# A tibble: 10 x 4
a b spline approx
<chr> <dbl> <dbl> <dbl>
1 group1 1 1 1
2 group1 2 2 2
3 group1 NA 3 3
4 group1 4 4 4
5 group2 1 1 1
6 group2 NA 1 1
7 group2 NA 1 1
8 group2 NA 1 1
9 group3 NA NA NA
10 group3 NA NA NA
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。