Search code examples
rfor-loopdplyrplyr

R - Add each vector element into a variable of a dataframe recursively


I have a list of people...

v <- c("John", "Paul", "Annie")

and I want to distribute them recursively accross 14 different rooms.

df1 <- data.frame(ROOM = c("ROOM01", "ROOM02", "ROOM03", "ROOM04", "ROOM05", "ROOM06", "ROOM07","ROOM08", "ROOM09","ROOM10","ROOM11","ROOM12", "ROOM13", "ROOM14"),
                  PERSON = NA)


> View(df1)
> df1
     ROOM PERSON
1  ROOM01     NA
2  ROOM02     NA
3  ROOM03     NA
4  ROOM04     NA
5  ROOM05     NA
6  ROOM06     NA
7  ROOM07     NA
8  ROOM08     NA
9  ROOM09     NA
10 ROOM10     NA
11 ROOM11     NA
12 ROOM12     NA
13 ROOM13     NA
14 ROOM14     NA

So, my desired dataset would be like that

     ROOM     PERSON
1  ROOM01     John
2  ROOM02     Paul
3  ROOM03     Annie
4  ROOM04     John
5  ROOM05     Paul
6  ROOM06     Annie
7  ROOM07     John
8  ROOM08     Paul
9  ROOM09     Annie
10 ROOM10     John
11 ROOM11     Paul
12 ROOM12     Annie
13 ROOM13     John
14 ROOM14     Paul

Any help would be very appreciated! Thanks


Solution

  • We can use rep with length.out as number of rows (nrow) of the data, which will recursively replicate until it reaches the limit

    df1$PERSON <- rep(v, length.out = nrow(df1))