Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr duplicate each line by a sequence

Tags:

r

dplyr

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()
like image 867
Wilcar Avatar asked Dec 14 '22 21:12

Wilcar


2 Answers

You can create a list column that contains 1:3 each and then unnest it:

library(dplyr); library(tidyr)
df %>% mutate(row_id = list(seq_len(3))) %>% unnest()

#  country page row_id
#1    belg    1      1
#2    belg    1      2
#3    belg    1      3
#4    belg    2      1
#5    belg    2      2
#6    belg    2      3
#7    belg    3      1
#8    belg    3      2
#9    belg    3      3

dput(df)
structure(list(country = structure(c(1L, 1L, 1L), .Label = "belg", class = "factor"), 
    page = 1:3), .Names = c("country", "page"), class = "data.frame", row.names = c(NA, 
-3L))
like image 126
Psidom Avatar answered Dec 16 '22 10:12

Psidom


Another option is to paste as a string and then with separate_rows split the rows

library(tidyverse)
df %>% 
  mutate(row_id = toString(seq_len(3))) %>% 
  separate_rows(row_id)
#  country page row_id
#1    belg    1      1
#2    belg    1      2
#3    belg    1      3
#4    belg    2      1
#5    belg    2      2
#6    belg    2      3
#7    belg    3      1
#8    belg    3      2
#9    belg    3      3
like image 36
akrun Avatar answered Dec 16 '22 12:12

akrun