How to increase the length of an R data frame by repeating the number of rows?

R ProgrammingServer Side ProgrammingProgramming

If we strongly believe that new data collection will result in the same type of data then we might want to stretch our data frame in R with more rows. Although, this is not recommended because we lose unbiasedness in the data due to this process but it is done to save time and money that will be invested in new data collection. In R, we can use rep with seq_len function to repeat the number of rows of an R data frame.

Example

Consider the below data frame −

> x1<-c("Fruits","Vegetables","Dry Fruits","Dairy")
> x2<-c(2,5,6,3)
> df<-data.frame(x1,x2)
> df
x1 x2
1 Fruits 2
2 Vegetables 5
3 Dry Fruits 6
4 Dairy 3

Repeating the number of rows twice but one repetition follows the other −

> df[rep(seq_len(nrow(df)),times=2),]
x1 x2
1 Fruits 2
2 Vegetables 5
3 Dry Fruits 6
4 Dairy 3
1.1 Fruits 2
2.1 Vegetables 5
3.1 Dry Fruits 6
4.1 Dairy 3

Repeating the number of rows five times but one repetition follows the other −

> df[rep(seq_len(nrow(df)),times=5),]
x1 x2
1 Fruits 2
2 Vegetables 5
3 Dry Fruits 6
4 Dairy 3
1.1 Fruits 2
2.1 Vegetables 5
3.1 Dry Fruits 6
4.1 Dairy 3
1.2 Fruits 2
2.2 Vegetables 5
3.2 Dry Fruits 6
4.2 Dairy 3
1.3 Fruits 2
2.3 Vegetables 5
3.3 Dry Fruits 6
4.3 Dairy 3
1.4 Fruits 2
2.4 Vegetables 5
3.4 Dry Fruits 6
4.4 Dairy 3

Repeating each row with equal number of times −

> df[rep(seq_len(nrow(df)),each=5),]
x1 x2
1 Fruits 2
1.1 Fruits 2
1.2 Fruits 2
1.3 Fruits 2
1.4 Fruits 2
  2 Vegetables 5
2.1 Vegetables 5
2.2 Vegetables 5
2.3 Vegetables 5
2.4 Vegetables 5
3 Dry Fruits 6
3.1 Dry Fruits 6
3.2 Dry Fruits 6
3.3 Dry Fruits 6
3.4 Dry Fruits 6
4        Dairy 3
4.1      Dairy 3
4.2      Dairy 3
4.3      Dairy 3
4.4      Dairy 3

Repeating the number of rows, a different number of times −

> df[rep(seq_len(nrow(df)),times=c(2,3,4,5)),]
x1 x2
1 Fruits 2
1.1 Fruits 2
2 Vegetables 5
2.1 Vegetables 5
2.2 Vegetables 5
3 Dry Fruits 6
3.1 Dry Fruits 6
3.2 Dry Fruits 6
3.3 Dry Fruits 6
4 Dairy 3
4.1 Dairy 3
4.2 Dairy 3
4.3 Dairy 3
4.4 Dairy 3
raja
Published on 11-Aug-2020 13:42:14
Advertisements