Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

I want to repeat the rows of a data.frame, each N times. The result should be a new data.frame (with nrow(new.df) == nrow(old.df) * N) keeping the data types of the columns.

Example for N = 2:

                        A B   C

  A B   C             1 j i 100

1 j i 100     -->     2 j i 100

2 K P 101             3 K P 101

                      4 K P 101

So, each row is repeated 2 times and characters remain characters, factors remain factors, numerics remain numerics, ...

My first attempt used apply: apply(old.df, 2, function(co) rep(co, each = N)), but this one transforms my values to characters and I get:

     A   B   C    

[1,] "j" "i" "100"

[2,] "j" "i" "100"

[3,] "K" "P" "101"

[4,] "K" "P" "101"

1 Answer

0 votes
by

To repeat rows of a data frame n times, you use the following methods:

df <- data.frame(A=c("j","K"), B=c("i","P"),C = c(100,101)) 

df[rep(seq_len(nrow(df)), each=2),]

 df[rep(seq_len(nrow(df)), each=2),]

    A B   C

1   j i 100

1.1 j i 100

2   K P 101

2.1 K P 101

Using dplyr:

 df %>% slice(rep(1:n(), each = 2))

  A B   C

1 j i 100

2 j i 100

3 K P 101

4 K P 101

Browse Categories

...