Search code examples
rrep

How to select and repeat a number of rows in a dataframe in r


I believe my question is quite simple, but I can't manage to find the right answer.

In any given dataframe:

> data.frame(x0=c(1,2,3,4), x1=rnorm(4))
  x0         x1
1  1 -0.1868765
2  2 -0.2935534
3  3 -1.3934953
4  4  0.8165035

Imagine I'd like to take every two rows and repeat it by 2 times ending up with something like this:

> data.frame(x0=c(1,2,3,4), x1=rnorm(4))
  x0         x1
1  1 -0.1868765
2  2 -0.2935534
3  1 -0.1868765
4  2 -0.2935534
5  3 -1.3934953
6  4  0.8165035
7  3 -1.3934953
8  4  0.8165035


What is the easiest way to do this?

Thanks in advance!


Solution

  • You can create group of 2 rows and repeat it twice for each group, unlist the indices and subset.

    set.seed(123)
    df <- data.frame(x0=c(1,2,3,4), x1=rnorm(4))
    
    inds <- seq(nrow(df))
    df[unlist(tapply(inds, ceiling(inds/2), rep, 2)), ]
    
    #    x0          x1
    #1    1 -0.56047565
    #2    2 -0.23017749
    #1.1  1 -0.56047565
    #2.1  2 -0.23017749
    #3    3  1.55870831
    #4    4  0.07050839
    #3.1  3  1.55870831
    #4.1  4  0.07050839