1

I have a df:

> df
# A tibble: 3 x 2
   Class word    
   <fct> <chr>   
 1 Y     nature
 2 Y     great
 3 Y     are     

I would like to repeat each value in word a specific number of times. For example, I want to repeat it 4 times:

> df
# A tibble: 12 x 2
   Class word    
   <fct> <chr>   
 1 Y     nature
 2 Y     nature
 3 Y     nature     
 4 Y     nature
 5 Y     great
 6 Y     great
 7 Y     great
 8 Y     great
 9 Y     are
10 Y     are
11 Y     are
12 Y     are

How do I do this using rep()?

2 Answers2

5

We can use uncount

library(tidyr)
library(dplyr)
df %>%
    uncount(4) %>%
    as_tibble

Or with rep

df[rep(seq_len(nrow(df)), each = 4),]
akrun
  • 789,025
  • 32
  • 460
  • 575
1

We could use this:

library(dplyr)
df %>% slice(rep(1:n(), each = 4))
TarJae
  • 43,365
  • 4
  • 14
  • 40