Home > Software design >  Create R dataset with userid repeated each x times
Create R dataset with userid repeated each x times

Time:07-08

I have a vector containing user_id (1,2,3,4,5), and i want to create a dataset where each user_id is repeated 3 times:

userid   time
1         1
1         2
1         3
2         1
2         2
2         3
3         1
3         2
3         3
...

CodePudding user response:

df <- data.frame(
  user_id = rep(1:5, each = 3),
  time = rep(1:3, times = 5)
)

df

#>    user_id time
#> 1        1    1
#> 2        1    2
#> 3        1    3
#> 4        2    1
#> 5        2    2
#> 6        2    3
#> 7        3    1
#> 8        3    2
#> 9        3    3
#> 10       4    1
#> 11       4    2
#> 12       4    3
#> 13       5    1
#> 14       5    2
#> 15       5    3

Created on 2022-07-07 by the reprex package (v2.0.1)

CodePudding user response:

You can use rep with argument each = 3

> user_id <- 1:5

> data.frame(userid = rep(user_id, each = 3), time = 1:3)
   userid time
1       1    1
2       1    2
3       1    3
4       2    1
5       2    2
6       2    3
7       3    1
8       3    2
9       3    3
10      4    1
11      4    2
12      4    3
13      5    1
14      5    2
15      5    3

or expand.grid

> rev(expand.grid(time = 1:3, userid = 1:5))
   userid time
1       1    1
2       1    2
3       1    3
4       2    1
5       2    2
6       2    3
7       3    1
8       3    2
9       3    3
10      4    1
11      4    2
12      4    3
13      5    1
14      5    2
15      5    3
  • Related