Jihong
Jihong

Reputation: 163

How to add rows based on group while iteravely adding one?

Does anyone have a way to add rows by group to a certain length without having to create new dataframes?This is my current dataframe with columns "Group" and "Amount"

Group   Amount
 Dog      1
 Dog      2
 Dog      3
 Cat      3
 Cat      4
 Rat      7
 Rat      8
 Rat      9
 Rat      10

I'm trying to make them all equal lengths so they can look as shown below:

Group   Amount
 Dog      1
 Dog      2
 Dog      3
 Dog      4
 Dog      5
 Dog      6
 Dog      7
 Cat      3
 Cat      4
 Cat      5
 Cat      6
 Cat      7
 Cat      8
 Cat      9
 Rat      7
 Rat      8
 Rat      9
 Rat      10
 Rat      11
 Rat      12
 Rat      13

Where I want each group to be length seven and iteravely just add one to the tail end of the group until they reach the desired length.

Thanks

Upvotes: 1

Views: 61

Answers (2)

akrun
akrun

Reputation: 887158

We can group by 'Group' and then use complete to expand the rows

library(dplyr)
library(tidyr)
n <- 7
df1 %>% 
     group_by(Group) %>%
     complete(Amount = min(Amount):(min(Amount) + (n -1))) %>%
     as.data.frame

data

df1 <- structure(list(Group = c("Dog", "Dog", "Dog", "Cat", "Cat", "Rat", 
"Rat", "Rat", "Rat"), Amount = c(1L, 2L, 3L, 3L, 4L, 7L, 8L, 
9L, 10L)), class = "data.frame", row.names = c(NA, -9L))

Upvotes: 2

arg0naut91
arg0naut91

Reputation: 14764

In data.table:

library(data.table)

setDT(df)[, .(Amount = seq(min(Amount), min(Amount) + 6)), by = Group]

Output:

    Group Amount
 1:   Dog      1
 2:   Dog      2
 3:   Dog      3
 4:   Dog      4
 5:   Dog      5
 6:   Dog      6
 7:   Dog      7
 8:   Cat      3
 9:   Cat      4
10:   Cat      5
11:   Cat      6
12:   Cat      7
13:   Cat      8
14:   Cat      9
15:   Rat      7
16:   Rat      8
17:   Rat      9
18:   Rat     10
19:   Rat     11
20:   Rat     12
21:   Rat     13

Upvotes: 1

Related Questions