How to usereplicate() method in R Language
A replication factor is declared to define the number of times the data frame rows are to be repeated. The do.call() method in R is used to perform an R function while taking as input various arguments. The rbind() method is taken as the first argument of this method to combine data frames together. The second argument is the replicate() method which is used to create multiple copies of the rows of the data frames equivalent to the number of times same as replication factor.
Syntax: replicate(n, expr, simplify)
Parameter :
- n – Number of replications to be performed.
- expr – Expression to be performed repeatedly.
- simplify – Type of output the results of expr are saved into.
Example: Repeating rows n times
R
# creating a data frame data_frame <- data.frame (col1 = c (6:8), col2 = letters [1:3], col3 = c (1,4, NA )) print ( "Original DataFrame" ) print (data_frame) # replication factor n <- 3 data_frame_mod <- do.call ( "rbind" , replicate ( n, data_frame, simplify = FALSE )) print ( "Modified DataFrame" ) print (data_frame_mod) |
Output
[1] "Original DataFrame" col1 col2 col3 1 6 a 1 2 7 b 4 3 8 c NA [1] "Modified DataFrame" col1 col2 col3 1 6 a 1 2 7 b 4 3 8 c NA 4 6 a 1 5 7 b 4 6 8 c NA 7 6 a 1 8 7 b 4 9 8 c NA
Repeat Rows of DataFrame N Times in R
In this article, we will discuss how to repeat rows of Dataframe for a given number of times using R programming language.
Contact Us