Search code examples
rdplyrspline

mutate does not work with na.spline/na.approx


I try to use na.approx() and na.spline() in a mutate, but the length of output vectors is wrong and I get the following error

 Error: Column `var_1 <- na.approx(var_1, na.rm = F)` must be length 1 (the group size), not 2

test <- tibble(group_1 = c(1,1,1,1,1),group_2 = c(1,1,1,2,2),var_1 = c(1,NA,2,1,NA),var_2 = c(1,1,NA,NA,NA))

  group_1 group_2 var_1 var_2
    <dbl>   <dbl> <dbl> <dbl>
1       1       1     1     1
2       1       1    NA     1
3       1       1     2    NA
4       1       2     1    NA
5       1       2    NA    NA

test <- test %>% 
  group_by(group_1,group_2) %>% 
  mutate(
    var_1 <- na.approx(var_1,na.rm = F),
    var_2 <- na.spline(var_2,na.rm = F))

Desired:

# A tibble: 5 x 4
  group_1 group_2 var_1 var_2
    <dbl>   <dbl> <dbl> <dbl>
1       1       1   1       1
2       1       1   1.5     1
3       1       1   2       1
4       1       2   1      NA
5       1       2   1      NA

Edits:

When I use the solution suggested by @akrun I still get:

Error: Column `var_1` must be length 16 (the group size) or one, not 14

Solution

  • What worked in the end was this:

    test <- test %>% 
      group_by(group_1,group_2) %>% 
      arrange(group_1) %>%
      mutate(
        var_1 = na.approx(var_1,na.rm = FALSE),
        var_1 = if(all(is.na(var_1))) NA else na.spline(var_1,na.rm = FALSE),
        var_2 = if(all(is.na(var_2))) NA else na.spline(var_2,na.rm = FALSE))