You can use the following methods to replicate rows in a data frame in R using functions from the dplyr package:
Method 1: Replicate Each Row the Same Number of TimesÂ
library(dplyr) #replicate each row 3 times df %>% slice(rep(1:n(), each = 3))
Method 2: Replicate Each Row a Different Number of Times
library(dplyr) #replicate the first row 3 times and the second row 5 times df %>% slice(rep(1:n(), times = c(3, 5)))
The following examples show how to use each method in practice.
Example 1: Replicate Each Row the Same Number of Times
Suppose we have the following data frame with two rows in R:
#create data frame
df frame(team=c('A', 'B'),
points=c(10, 15),
rebounds=c(4, 8),
assists=c(2, 5))
#view data frame
df
team points rebounds assists
1 A 10 4 2
2 B 15 8 5
We can use the following syntax to repeat each row in the data frame three times:
library(dplyr)
#create new data frame that repeats each row in original data frame 3 times
new_df % slice(rep(1:n(), each = 3))
#view new data frame
new_df
team points rebounds assists
1 A 10 4 2
2 A 10 4 2
3 A 10 4 2
4 B 15 8 5
5 B 15 8 5
6 B 15 8 5
Notice that each of the rows from the original data frame have been repeated three times.
Example 2: Replicate Each Row a Different Number of Times
Suppose we have the following data frame with two rows in R:
#create data frame
df frame(team=c('A', 'B'),
points=c(10, 15),
rebounds=c(4, 8),
assists=c(2, 5))
#view data frame
df
team points rebounds assists
1 A 10 4 2
2 B 15 8 5
We can use the following syntax to repeat the first row three times and the second row five times:
library(dplyr)
#create new data frame that repeats first row 3 times and second row 5 times
new_df % slice(rep(1:n(), times = c(3, 5)))
#view new data frame
new_df
team points rebounds assists
1 A 10 4 2
2 A 10 4 2
3 A 10 4 2
4 B 15 8 5
5 B 15 8 5
6 B 15 8 5
7 B 15 8 5
8 B 15 8 5
Notice that the first row in the original data frame has been repeated three times and the second row has been repeated five times.
Related: How to Use the slice() Function in dplyr
Additional Resources
The following tutorials explain how to perform other common operations in dplyr:
How to Select Columns by Index Using dplyr
How to Select the First Row by Group Using dplyr
How to Filter by Multiple Conditions Using dplyr
How to Filter Rows that Contain a Certain String Using dplyr