A tidyverse
solution. Reshape your data twice to make it long (reshaping by names and then id). Use separate
to find the "suffix` of the names and ids, then filter on the suffixes matching.
library(tidyverse)
df %>%
pivot_longer(cols = starts_with("Name"), names_to = "name_names", values_to = "name") %>%
pivot_longer(cols = starts_with("ID"), names_to = "id_names", values_to = "id") %>%
separate(col = name_names, into = c("name_names", "suffix_names")) %>%
separate(col = id_names, into = c("id_names", "suffix_id")) %>%
filter(suffix_names == suffix_id) %>%
select(name, id)
# A tibble: 20 x 2
name id
<fct> <int>
1 A 1
2 K 11
3 B 2
4 L 12
5 C 3
6 M 13
7 D 4
8 N 14
9 E 5
10 O 15
11 F 6
12 P 16
13 G 7
14 Q 17
15 H 8
16 R 18
17 I 9
18 S 19
19 J 10
20 T 20