Repeat Rows of Data Frame N Times in R (2 Examples)
This tutorial illustrates how to create (multiple) duplicates of each row of a data frame in the R programming language.
The article will consist of these contents:
Let’s do this.
Creation of Example Data
Consider the following example data:
data <- data.frame(x1 = 1:5, x2 = LETTERS[1:5]) data # x1 x2 # 1 1 A # 2 2 B # 3 3 C # 4 4 D # 5 5 E
The previous output of the RStudio console shows that our example data contains five rows and two columns.
Example 1: Create Repetitions of Data Frame Rows Using Base R
This Example illustrates how to create repetitions of our data frame rows. Let’s assume that we want to repeat each line of our matrix three times. Then, we can use the rep, seq_len, and nrow functions as shown below:
data_new_1 <- data[rep(seq_len(nrow(data)), each = 3), ] # Base R data_new_1 # x1 x2 # 1 1 A # 1.1 1 A # 1.2 1 A # 2 2 B # 2.1 2 B # 2.2 2 B # 3 3 C # 3.1 3 C # 3.2 3 C # 4 4 D # 4.1 4 D # 4.2 4 D # 5 5 E # 5.1 5 E # 5.2 5 E
The previous output is showing our result: A data frame with three duplicates of each row. Note that the row names are numerated with .1, .2 and so on.
Example 2: Create Repetitions of Data Frame Rows Using dplyr Package
This Section illustrates how to duplicate lines of a data table (or a tibble) using the dplyr package. In case we want to use the functions of the dplyr package, we first need to install and load dplyr:
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package
Now, we can apply the slice, rep, and n functions as follows:
data_new_2 <- data %>% slice(rep(1:n(), each = 3)) # dplyr package data_new_2 # x1 x2 # 1 1 A # 2 1 A # 3 1 A # 4 2 B # 5 2 B # 6 2 B # 7 3 C # 8 3 C # 9 3 C # 10 4 D # 11 4 D # 12 4 D # 13 5 E # 14 5 E # 15 5 E
The values contained in the output data are the same as in Example 1. However, when using the dplyr package the row names have a range from 1 to the number of rows of your data.
Video, Further Resources & Summary
I have recently published a video on my YouTube channel, which illustrates the examples of this article. You can find the video below.
The YouTube video will be added soon.
Furthermore, you might have a look at the related articles of this website:
- rep Function in R
- The nrow Function in R
- Introduction to dplyr Package in R
- How to Remove Duplicated Rows from Data Frame in R
- The R Programming Language
In this R tutorial you learned how to repeat lines of a matrix table. Let me know in the comments section below, if you have any additional questions or comments.
Statistics Globe Newsletter