Search code examples
rrep

Duplicating values in a column


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()?


Solution

  • We can use uncount

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

    Or with rep

    df[rep(seq_len(nrow(df)), each = 4),]