Repeat dataframe N times and add flag column to identify each repeated dataframe

Hi dears,
Hope all of you great. Although i'm worked with R for doing some tasks and i'm totally interested , but i faced a task that needed some time from me to do. I have a DF with 3 attributes and 2k rows. I Need to repeat all these rows for 31 times (Number of days in Month Jan for example ) and add column to identify each repeated number which will be a date , each repetition is for a day. How can i do that please ?

Here are a couple of approaches for this problem.

Since we don't have your data, I'll use the palmerpenguins dataset for demonstration:

library(palmerpenguins)
library(purrr)

df <- penguins[,c("species","island","sex")]

One approach is to use base R functions:

day_df <- do.call(
  rbind,
  lapply(
    1:31,
    function(i) {
      df$day <- i
      df
    }
  ))

Here, we're using lapply to make a list of modified data.frames, each of which has a value, from 1 to 31, in the "day" column. We then assemble these into a single data.frame by running do.call(rbind).

Here's a second approach using the purrr package:

add_day <- function(day, df) {
  df$day <- day
  df
}

day_df <- map_dfr(
  1:31,
  add_day,
  df = df
)

In this case, we're making a simple function add_day(), then using map_dfr() from purrr to assemble the data.frames into a single result.

Note: we could also use an anonymous function just like in the base example:

day_df <- map_dfr(
  1:31,
  function(day) {
    df$day <- day
    df
  }
)
2 Likes

a variation using dplyr::bind_rows

library(palmerpenguins)
library(tidyverse)
df <- penguins[,c("species","island","sex")]

#solution
new_df <- map(seq_len(31),~df) %>% 
  bind_rows(.id="id")

#check it out
head(new_df)
tail(new_df)
2 Likes

thank you so much for your time to support and your neat code :slight_smile:

thank you so much for your support @nirgrahamuk

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.