repeat dataframe n times whilst adding column

  • A+
Category:Languages

This is my reproducible code:

df <- data.frame(x = c(1, 2), y = c(3, 4))  df1 <- df %>% mutate(z = 1) df2 <- df %>% mutate(z = 2) df3 <- df %>% mutate(z = 3)  df <- rbind(df1, df2, df3)  df 

I repeat the original data frame df 3 times, whilst adding one column where the number in the column indicated the repetition. In my use case, I have to do this more than 3 times. I could use a loop but is there a neater way? I guess i cannot use expand.grid.

 


We can create a list column and unnest

library(tidyverse) df %>%    mutate(z = list(1:3)) %>%    unnest %>%    arrange(z) #  x y z #1 1 3 1 #2 2 4 1 #3 1 3 2 #4 2 4 2 #5 1 3 3 #6 2 4 3 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: