How can I interleave rows from 2 data frames together like a perfect riffle shuffle?
Example data:
df1 <- data.frame(df = 1, id = 1:5, chr = 'puppies')
df2 <- data.frame(df = 2, id = 1:5, chr = 'kitties')
df1:
df id chr
1 1 1 puppies
2 1 2 puppies
3 1 3 puppies
4 1 4 puppies
5 1 5 puppies
df2:
df id chr
1 2 1 kitties
2 2 2 kitties
3 2 3 kitties
4 2 4 kitties
5 2 5 kitties
Desired result:
df id chr
1 1 1 puppies
2 2 1 kitties
3 1 2 puppies
4 2 2 kitties
5 1 3 puppies
6 2 3 kitties
7 1 4 puppies
8 2 4 kitties
9 1 5 puppies
10 2 5 kitties
A non-dplyr solution would be to use the interleave
function in the gdata
package.
gdata::interleave(df1, df2)
Assign row numbers to each data frame independently, then bind the rows and sort/arrange by row number and data frame id. In this example, row numbers are trivial since the ids are sequential and act as row number. But in the general case, row numbers should be used.
Here's an example using dplyr:
df1 %>%
mutate(row_number = row_number()) %>%
bind_rows(df2 %>% mutate(row_number = row_number())) %>%
arrange(row_number, df)
Output:
df id chr row_number
(dbl) (int) (chr) (int)
1 1 1 puppies 1
2 2 1 kitties 1
3 1 2 puppies 2
4 2 2 kitties 2
5 1 3 puppies 3
6 2 3 kitties 3
7 1 4 puppies 4
8 2 4 kitties 4
9 1 5 puppies 5
10 2 5 kitties 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With