0

I have a data.frame with n rows and I would like to repeat this rows according to the observation of another variable

This is an example for a data.frame

df <- data.frame(a=1:3, b=letters[1:2]) 
df

  a b
1 1 a
2 2 b
3 3 c

And this one is an example for a variable

df1 <- data.frame(x=1:3)
df1

  x
1 1
2 2
3 3

In the next step I would like to repeat every row from the df with the observation of df1

So that it would look like this

  a b
1 1 a
2 2 b
3 2 b
4 3 c
5 3 c
6 3 c

If you have any idea how to solve this problem, I would be very thankful

camille
  • 16,432
  • 18
  • 38
  • 60
luga96
  • 1

1 Answers1

0

You simply can repeat the index like:

df[rep(1:3,df1$x),]
#    a b
#1   1 a
#2   2 b
#2.1 2 b
#3   3 c
#3.1 3 c
#3.2 3 c

or not fixed to size 3

df[rep(seq_along(df1$x),df1$x),]
GKi
  • 37,245
  • 2
  • 26
  • 48