Search code examples
rduplicatesrep

Duplicating rows to match a new data frame


I am working with R and I have two tibbles (data frames) that are related, but for now they are separated. For each row of the first tibble, they are ten (10) or less rows that are related to that tibble. So, my first tibble look like this...

A  0.1
B  0.2
C  0.3
D  0.4
E  0.5

The second tibble look like this...

A  1.5
A  1.6
A  1.7
A  1.8
A  1.9
B  2.5
B  2.6
B  2.7
B  2.8
B  2.9
C  3.1
C  3.3
D  4.4
D  4.6
E  6.6
E  6.7

So, I need to duplicate the values of the first tibble in order to match the second tibble. So, I need the first tibble to look like this...

A  0.1
A  0.1
A  0.1
A  0.1
A  0.1
B  0.2
B  0.2
B  0.2
B  0.2
B  0.2
C  0.3
C  0.3
D  0.4
D  0.4
E  0.5
E  0.5

The problem that I have is that the number of times that the values are repeated on the second tibble is not consistent. So, sometimes the values of the first tibble need to be duplicated x5 times, x2 times, etc.

How can I duplicate the values of the first tibble if they need to be duplicated in an inconsistent manner. Some 5, some 2, Some 3, etc etc.

*The first tibble have 600 values.


Solution

  • Select only the first column of tibble2 then left join with tibble1.

    library(tidyverse)
    
    tibble2 %>%
        select(col1) %>%
        left_join(tibble1, by = 'col1')