Home > OS >  Is there a function to stack multiple duplicate dataframes
Is there a function to stack multiple duplicate dataframes

Time:12-24

Just wondering if there was a function that could stack the same dataframe multiple times. Here is an example whereby I stack same dataframe three times on top of each other.

df <- mtcars

df <- rbind(df,df,df) # here stack same df three times

Is there a function that can stack the same dataframes mulitple times, where you only need specify the number of times to be duplicated. I could write a loop to do it, but is there function that can do it like this

df <- stack(df , 3) # does a function like this exist?

Any help greatly appreciated. Thanks

CodePudding user response:

Not in a package that I know of, but you can do this either in a one liner, or create a custom function.

Custom function:

stack_df <- function(dataframe, ntimes) {
  as.data.frame(sapply(dataframe, rep.int, times = ntimes))
}
stack_df(dataframe = mtcars, ntimes = 3)

One liner:

as.data.frame(sapply(mtcars, rep.int, times = 3))
  •  Tags:  
  • r
  • Related