I have this list of lists:
regions <- list(c("AO", "BI", "BW", "DJ", "DZ", "ET", "GH", "GM", "KE", "LS", "MA", "MR", "MW", "MZ", "NG", "SL", "SZ", "TN", "TZ", "UG", "ZA", "ZM", "ZR", "ZW"),
c("BD", "CN", "HK", "ID", "IN", "KR", "MU", "MY", "PH", "PK", "SG", "TH", "TW", "VN", "AU", "NZ"),
c("AT", "BA", "BE", "BL", "CH", "CI", "CT", "CY", "CZ", "DE", "DK", "EO", "ES", "EU", "FI", "FR", "GA", "GB", "GG", "GR", "HU", "IC", "IE", "IT", "JR", "KZ", "LN", "LU", "LV", "MK", "MT", "NL", "NO", "PO", "PT", "RM", "RS", "RU", "SE", "SJ", "SX", "TR", "UR"),
c("AD", "AE", "BH", "DU", "EG", "IQ", "IR", "IS", "JO", "KW", "LB", "OM", "PS", "QA", "SA", "SY", "YE"),
c("CA", "KY", "US"),
c("AR", "BR", "CB", "CL", "EC", "MX", "PA", "PE", "PY", "UY", "VE"),
c("JP"))
There are 7 lists, and I would like this data in a tibble format, with a region ID for each list:
country | region_id
"AO" | 1
"BI" | 1
"BW" | 1
...
"BD" | 2
"CN" | 2
"HK" | 2
...
Use enframe
+ unnest
:
library(tibble)
enframe(regions, "region_id", "country") |>
unnest(country)
In base R, name the list, and use stack
:
setNames(regions, seq_along(regions)) |>
stack()
output
region_id country
1 1 AO
2 1 BI
3 1 BW
4 1 DJ
5 1 DZ
6 1 ET
7 1 GH
8 1 GM
9 1 KE
10 1 LS
11 1 MA
12 1 MR
13 1 MW
14 1 MZ
15 1 NG
16 1 SL
17 1 SZ
18 1 TN
19 1 TZ
20 1 UG
21 1 ZA
22 1 ZM
23 1 ZR
24 1 ZW
25 2 BD
26 2 CN
27 2 HK
28 2 ID
29 2 IN
30 2 KR
31 2 MU
32 2 MY
33 2 PH
34 2 PK
35 2 SG
36 2 TH
37 2 TW
38 2 VN
39 2 AU
40 2 NZ
41 3 AT
42 3 BA
43 3 BE
44 3 BL
45 3 CH
46 3 CI
47 3 CT
48 3 CY
49 3 CZ
50 3 DE
51 3 DK
52 3 EO
53 3 ES
54 3 EU
55 3 FI
56 3 FR
57 3 GA
58 3 GB
59 3 GG
60 3 GR
61 3 HU
62 3 IC
63 3 IE
64 3 IT
65 3 JR
66 3 KZ
67 3 LN
68 3 LU
69 3 LV
70 3 MK
71 3 MT
72 3 NL
73 3 NO
74 3 PO
75 3 PT
76 3 RM
77 3 RS
78 3 RU
79 3 SE
80 3 SJ
81 3 SX
82 3 TR
83 3 UR
84 4 AD
85 4 AE
86 4 BH
87 4 DU
88 4 EG
89 4 IQ
90 4 IR
91 4 IS
92 4 JO
93 4 KW
94 4 LB
95 4 OM
96 4 PS
97 4 QA
98 4 SA
99 4 SY
100 4 YE
101 5 CA
102 5 KY
103 5 US
104 6 AR
105 6 BR
106 6 CB
107 6 CL
108 6 EC
109 6 MX
110 6 PA
111 6 PE
112 6 PY
113 6 UY
114 6 VE
115 7 JP