These sorts of problems are much easier to tackle if you first pivot the data into long form.
library(dplyr, warn.conflicts = FALSE)
library(tidyr)
df <- tibble(
Origin = c(5, 7, 3, 12, 2, 6, 8, 5, 8, 9, 12, 3, 12, 9, 4, 4, 2, 4, 4),
Destination_1 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_2 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_3 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_4 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_5 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_6 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_7 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_8 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_9 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_10 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_11 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_12 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
Destination_13 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
)
df %>%
pivot_longer(starts_with("Destination"), names_prefix = "Destination_") %>%
mutate(value = if_else(Origin == as.numeric(name), 0, value)) %>%
pivot_wider(names_prefix = "Destination_", values_fn = list) %>%
unnest(starts_with("Destination")) %>%
print(n = 10, width = 70)
#> # A tibble: 19 x 14
#> Origin Destination_1 Destination_2 Destination_3 Destination_4
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 5 1 1 1 1
#> 2 5 1 1 1 1
#> 3 7 1 1 1 1
#> 4 3 1 1 0 1
#> 5 3 1 1 0 1
#> 6 12 1 1 1 1
#> 7 12 1 1 1 1
#> 8 12 1 1 1 1
#> 9 2 1 0 1 1
#> 10 2 1 0 1 1
#> # ... with 9 more rows, and 9 more variables: Destination_5 <dbl>,
#> # Destination_6 <dbl>, Destination_7 <dbl>, Destination_8 <dbl>,
#> # Destination_9 <dbl>, Destination_10 <dbl>, Destination_11 <dbl>,
#> # Destination_12 <dbl>, Destination_13 <dbl>
Created on 2020-09-08 by the reprex package (v0.3.0)
The tricky bit here is that the values in Origin aren't unique so pivot_wider() generates list-cols which then need to be unnested. A consequence is that the row order of the input isn't preserved but I don't think there is a way around it.