Wilcar Wilcar - 23 days ago 8
R Question

fill a column proportionally based on a list of values ​(which may vary)

Fill a column proportionally based on a list of values ​​(which may vary)
Exemple :

id <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
id <- as.data.frame(id)

names <- c("Jean", "Jules", "Lina")
names <- as.data.frame(names)


Expected output :

id names
1 Jean
2 Jean
3 Jean
4 Jules
5 Jules
6 Jules
7 Lina
8 Lina
9 Lina
10 Lina


I must adapt my second column values with any list like this example :

id2 <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11)
id2 <- as.data.frame(id2)
names2 <- c("Jean", "Jules", "Lina", "Fred")
names2 <- as.data.frame(names2)


Expected output :

id2 names2
1 Jean
2 Jean
3 Jean
4 Jules
5 Jules
6 Jules
7 Lina
8 Lina
9 Lina
10 Fred
11 Fred


I have no idea how to do this.

Answer Source

You can calculate the number of repetitions by dividing the number of lines by the number of names, then use tidyr::fill to fill missing values.

# Number of repetitions:
n <- nrow(id) %/% nrow(names)

# Repeat names
repnames <- rep(names$names, each = n)

# Make the names vector the same length as id
repnames <- repnames[1:nrow(id)]

# Change it to a data frame
repnames <- data.frame(names = repnames)

# Add id column
repnames$id <- id$id

# Fill the missing value
repnames <- tidyr::fill(repnames, names)

repnames
# 
#    names id
# 1   Jean  1
# 2   Jean  2
# 3   Jean  3
# 4  Jules  4
# 5  Jules  5
# 6  Jules  6
# 7   Lina  7
# 8   Lina  8
# 9   Lina  9
# 10  Lina 10