Home > other >  How to complete column with zero using tidyr complete?
How to complete column with zero using tidyr complete?

Time:06-16

I have the following data frame:

library(tidyverse)
dat <- tribble(~id, ~pos, ~val, 
          "foo", 1, 10,
          "foo", 2, 5,
          "foo", 3, 1, 
          "bar", 3, 13)

Each id will have position (pos) from 1 to 3. What I want do to is to fill the id where there is incomplete pos and fill val with 0. The desired result is this:

  id      pos   val
 foo       1    10
 foo       2     5
 foo       3     1
 bar       1     0
 bar       2     0
 bar       3    13

How can I achieve that with tidyr complete()?

I tried this but didn't work:

  dat  %>% 
  group_by(id) %>% 
  complete(pos, fill = list(val = 0))

CodePudding user response:

Can be done using nesting within complete:

dat <- tribble(~id, ~pos, ~val, 
               "foo", 1, 10,
               "foo", 2, 5,
               "foo", 3, 1, 
               "bar", 3, 13)

dat %>% 
  complete(id, nesting(pos), fill = list(val = 0))

# A tibble: 6 × 3
  id      pos   val
  <chr> <dbl> <dbl>
1 bar       1     0
2 bar       2     0
3 bar       3    13
4 foo       1    10
5 foo       2     5
6 foo       3     1

CodePudding user response:

If you group the data, complete is applied to each group; so what you want to do is:

dat %>% complete(id, pos, fill = list(val = 0))

which gives you all id-pos-combinations, and fills missing val with zero.

  • Related