EML
EML

Reputation: 671

replacing missing value with non-values in grouped data using tidyverse

For each id, I am trying to replace missing values with data that is available.

library(tidyverse)
df <- data.frame(id=c(1,1,1,2,2,2,3), 
                 a=c(NA, NA, 10, NA, 12, NA, 10),
                 b=c(10, NA, NA, NA, 13,NA, NA))
> df
  id  a  b
1  1 NA 10
2  1 NA NA
3  1 10 NA
4  2 NA NA
5  2 12 13
6  2 NA NA
7  3 10 NA

I have tried:

df %>% 
  dplyr::group_by(id) %>%
  dplyr::mutate_at(vars(a:b), fill(., direction="up"))

and get the following error:

Error: 1 components of `...` had unexpected names.

We detected these problematic arguments:
* `direction`

Did you misspecify an argument?

Desired output:

  id  a  b
1  1 10 10
2  1 10 NA
3  1 10 NA
4  2 12 13
5  2 12 13
6  2 12 13
7  3 10 NA

Upvotes: 2

Views: 69

Answers (1)

akrun
akrun

Reputation: 886938

We dont' use fill with mutate_at. According to ?fill

data - A data frame. and

... - A selection of columns. If empty, nothing happens. You can supply bare variable names, select all variables between x and z with x:z, exclude y with -y. F

library(dplyr)
library(tidyr)
df %>%
    group_by(id) %>%
    fill(a:b, .direction = 'up')
# A tibble: 7 x 3
# Groups:   id [3]
#     id     a     b
#  <dbl> <dbl> <dbl>
#1     1    10    10
#2     1    10    NA
#3     1    10    NA
#4     2    12    13
#5     2    12    13
#6     2    NA    NA
#7     3    10    NA

Upvotes: 3

Related Questions