Search code examples
rdataframerepeatsequential

How to create new dataframe by repeating 1 column and sequentially repeating a 2nd column of original dataframe?


Im trying to create a new dataframe by repeating values in original-df column 1 and corresponding them to repeating values from original-df column 2. However, the values should repeat in a different manner for each column. For example, values from original-df column 1 will repeat as 1,2,3,1,2,3,1,2,3. Where as values from original-df column 2 should repeat as 1,1,1,2,2,2,3,3,3.

#here is original df
df1<-data.frame(x=1:3, y=10:12)

#I've tried the followig:
data.frame(x=df1$x,y=df1[,2])->df2

range<-1:3
data.frame(x=df1$x,y=df1$y[range,2])->df3

#I then tried this:
rep(df1$x,df1$y[l,2])->df4


#output either looks like this:
   x  y
1  1 10
2  2 11
3  3 12

#Or I receive an error message:
Error in df1$y[1, 2] : incorrect number of dimensions


#I expect data output to look like this:
  x  y
  1  10
  2  10
  3  10
  1  11
  2  11
  3  11
  1  12
  2  12
  3  12

Solution

  • An option would be expand

    library(tidyr)
    expand(df1, x, y)
    

    Or with expand.grid from base R

    do.call(expand.grid, df1)