Home > Back-end >  Add n (empty) rows per group_by
Add n (empty) rows per group_by

Time:10-06

I want to 'unaggregate' rows of data.

For example, I want to turn this table

  ID Allocated Remaining
1  A         2         4
2  B         1         2
3  C         0         1

into this table:

   ID Sourced
1   A       1
2   A       1
3   A       0
4   A       0
5   A       0
6   A       0
7   B       1
8   B       0
9   B       0
10  C       0

I want to do this by grouping the rows by ID and then adding a number of rows for, first, every allocated point and, second, for every remaining data point.

Something like:

df <- df %>%
   group_by(ID) %>%
   do(add_row(.))

But I want a specific amount of rows to be added per group.

Does anybody know how to tackle this problem?

CodePudding user response:

How about this?

df %>%
  group_by(ID)  %>%
  transmute(
    Sourced=list(c(rep(1,Allocated), rep(0,Remaining)))
    ) %>%  
  unnest

  ID    Sourced
   <chr>   <dbl>
 1 A           1
 2 A           1
 3 A           0
 4 A           0
 5 A           0
 6 A           0
 7 B           1
 8 B           0
 9 B           0
10 C           0

CodePudding user response:

df %>%
  pmap_dfr(~tibble(ID = ..1, Sourced = c(rep(1, ..2), rep(0, ..3))))

CodePudding user response:

Since summarise can return more than one row you may use -

library(dplyr)

df %>%
  group_by(ID) %>%
  summarise(Sourced = rep(c(1, 0), c(Allocated, Remaining)), .groups = 'drop')

#   ID    Sourced
#   <chr>   <dbl>
# 1 A           1
# 2 A           1
# 3 A           0
# 4 A           0
# 5 A           0
# 6 A           0
# 7 B           1
# 8 B           0
# 9 B           0
#10 C           0
  •  Tags:  
  • r
  • Related