How to repeat rows until a certain number of rows is reached in R

Viewed 46

I need to make a data frame from two data frame that their row number is different. I need to repeat rows of the smaller one as long as they have an equal number of rows. It is better to choose the rows to repeat randomly. for example: The first data frame:

#  A  B 
#x 12 13
#y 15 16

The second data frame:

#   C  D
#z  19 20
#w  20 30
#r  10 13
#k  54 32
#f  34 10

And I want the result to be:

#  A  B  C  D
#1 12 13 19 20
#2 15 16 20 30
#3 15 16 10 13
#4 12 13 54 32
#5 12 13 34 10
1 Answers

We may use rep with sample

if(nrow(df2) > nrow(df1)) {

  i1 <- sample(rep(seq_len(nrow(df1)), length.out = nrow(df2)))
  out <- cbind(df1[i1,], df2)
} else {

  i1 <- sample(rep(seq_len(nrow(df2)), length.out = nrow(df1)))
  out <- cbind(df1, df2[i1,])
}

row.names(out) <- NULL

-output

> out
   A  B  C  D
1 12 13 19 20
2 12 13 20 30
3 15 16 10 13
4 12 13 54 32
5 15 16 34 10

data

df1 <- structure(list(A = c(12L, 15L), B = c(13L, 16L)), 
class = "data.frame", row.names = c("x", 
"y"))

df2 <- structure(list(C = c(19L, 20L, 10L, 54L, 34L), D = c(20L, 30L, 
13L, 32L, 10L)), class = "data.frame", row.names = c("z", "w", 
"r", "k", "f"))
Related