dplyr duplicate each line by a sequence

Viewed 937

Dplyr: how to repeat each row based on a sequence of integers (1:3)

I am working on a register (about Belgium for exemple) :

country<- c("belg")
country <- as.data.frame(country)

The registery contains 3 pages :

library(dplyr)

country2 <- country %>%
   slice(rep(1:n(), each=3)) %>% 
   mutate(pages = row_number())

My output :

  country page 
  belg     1
  belg     2
  belg     3

Expected result : Each Register'pages contains three rows (repeat each row based on a sequence of integers (1:3))

  country page row_id
  belg     1   1
  belg     1   2
  belg     1   3 
  belg     2   1
  belg     2   2
  belg     2   3
  ...

What I tried :

Adding this to my dplyr's pipe :

     %>%
     group_by(pages) %>% 
     mutate(row_id = seq(1:3)) %>%
     ungroup()
2 Answers
Related