I was looking for a similar (but slightly different) solution. Post here if it is useful to someone else.
In my case, I needed a more general solution that allows each letter to be repeated an arbitrary number of times. Here is what I came up with:
library(tidyverse) df <- data.frame(letters = letters[1:4]) df > df letters 1 a 2 b 3 c 4 d
Say I want 2 A, 3 B, 2 C and 4 D:
df %>% mutate(count = c(2, 3, 2, 4)) %>% group_by(letters) %>% expand(count = seq(1:count))
If you do not want to store the count column:
df %>% mutate(count = c(2, 3, 2, 4)) %>% group_by(letters) %>% expand(count = seq(1:count)) %>% select(letters)
If you want the count to reflect the number of repetitions of each letter:
df %>% mutate(count = c(2, 3, 2, 4)) %>% group_by(letters) %>% expand(count = seq(1:count)) %>% mutate(count = max(count))
Brad Cannell Feb 28 '18 at 22:39 2018-02-28 22:39
source share