Dplyr: add rows to group_by groups

Is there a better way to add lines to group_by() groups than using bind_rows() ? Here is an example that is a little awkward:

 df <- data.frame(a=c(1,1,1,2,2), b=1:5) df %>% group_by(a) %>% do(bind_rows(data.frame(a=.$a[1], b=0), ., data.frame(a=.$a[1], b=10))) 

The idea is that the columns that we are already grouping can be derived from groups.

I was wondering if something like this might work:

 df %>% group_by(a) %>% insert(b=0, .at=0) %>% insert(b=10) 

Like append() , it can by default insert after all existing elements, and it can be smart enough to use group values ​​for any unspecified columns. Perhaps use NA for unordered columns.

Is there any convenient convenient syntax that I skipped, or will it be useful?

+6
source share
1 answer

Here's an approach using data.table :

 library(data.table) setDT(df) rbind(df, expand.grid(b = c(0, 10), a = df[ , unique(a)]))[order(a, b)] 

Depending on your actual context, this simpler alternative will work too:

 df[ , .(b = c(0, b, 10)), by = a] 

(and we can just use c(0, b, 10) in j if we don't care about keeping name b )

The first has the advantage that it will work even if df has more columns - just set fill = TRUE for rbind.data.table .

+2
source

All Articles