How to use rep() method In R Language
The nrow() method in R is used to determine the number of rows of the data frame.
Syntax:
nrow(data-frame)
The vector sequence is then generated using the seq_len() method described in the previous method. This is followed by the application of rep() method which is used to replicate numeric values a specified number of times. The first argument is the vector generated by seq_len() method and n is the replication factor.
Syntax:
rep(vec, n)
Data frame indexing is used to append the generated rows to the original data frame rows and stored as the modified data frame.
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 <- data_frame[ rep ( seq_len ( nrow (data_frame)), n), ] 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 1.1 6 a 1 2.1 7 b 4 3.1 8 c NA 1.2 6 a 1 2.2 7 b 4 3.2 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.