-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentire_workflow.qmd
1977 lines (1716 loc) · 55.4 KB
/
entire_workflow.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Thesis - Import Files"
toc: true
number-sections: true
format: gfm
warning: false
output: false
error: true
editor_options:
markdown:
wrap: sentence
---
# Setup
## Load libraries
```{r}
library(conflicted)
library(tidyverse)
library(readxl)
library(httr)
library(rvest)
library(reldist)
library(scales)
library(timeDate)
library(gtsummary)
library(tidymodels)
library(rtlr)
library(extrafont)
library(ggrepel)
# library(rvest)
# locale("he")
```
## Library conflicts
```{r}
conflicts_prefer(dplyr::filter())
```
## Graphics
```{r}
theme_set(theme_minimal())
theme_update(
text = element_text(family = "David")
)
decile_labs <- c(
"חלקם של 50% התחתונים בתקציב התרבות",
"חלקם של העשירונים השישי עד התשיעי בתקציב התרבות",
"חלקו של העשירון העליון בתקציב התרבות"
)
sector_labs <- c(
"רשויות עם רוב יהודי",
"רשויות עם רוב ערבי"
)
hypo_labs <- c(
"ערך מדד היפותטי",
"ערך מדד בפועל"
)
muni_type_colors <- c(
"עירייה" = "#F8766D",
"מועצה אזורית" = "#00BA38",
"מועצה מקומית" = "#619CFF"
)
```
# Utility functions
This function finds the file extension of a file.
It receives a string as an argument, and returns the last letters and numbers of the string, prefixed by a dot (`.`).
This helps to identify the file type from a file path, mainly used to write temporary files to disk when reading Excel files.
## Get file extension
```{r}
get_file_ext <- function(string) {
str_c(".", str_extract(string, "[0-9a-z]+$"))
}
```
## Read online Excel file
This function reads an Excel file from a url online.
It receives a url and other arguments used by `read_excel()`, and returns the tibble after being read.
```{r}
read_excel_url <- function(url, ...) {
GET(url, write_disk(tf <- tempfile(fileext = get_file_ext(url))))
read_excel(tf, ...)
}
```
## Fix column names
This function helps to fix column names of Excel tables, mainly of the form of those found in Israeli CBS municipality data.
It does so by fixing a single row of to-be column names.
It receives a data frame, an integer number representing a single row considered as holding (some of the) variable names, and a logical length-one vector specifying whether to fill missing values with preceding values or not.
This last argument is mostly used in the case of merged cells in Excel files.
The function first transposes the row, and then either fills it with values or turns NAs to empty strings.
```{r}
fix_names <- function(data, row_num, fill_missing) {
data <- data |>
slice(row_num) |>
pivot_longer(everything()) |>
select(value)
if (fill_missing) {
data <- data |>
fill(value)
}
else {
data <- data |>
replace_na(list(value = "")) |>
mutate(
value = if_else(
str_length(value) > 0,
str_c(" ", value),
value
)
)
}
data |>
pull(value)
}
```
This function fixes column names of Excel tables, mainly of the form of those found in Israeli CBS municipality data.
It receives a data frame, a vector with the row numbers considered as holding the variable names, and a logical vector specifying whether to fill missing values with preceding values or not.
This last argument should be either of length 1, or of length of `row_num`.
It is mostly used in the case of merged cells in Excel files.
The function saves the new column names by iterating over every row, fixing the variable names, binding all names to a single tibble, uniting the different columns to a single column and pulling these values as a vector.
The old rows containing these column names are filtered out, and the new merged and fixed names are set to the data frame, which is then returned.
```{r}
merge_names <- function(data, names_num = 2, fill_missing = TRUE) {
rows <- seq(names_num)
col_names_merged <- map2(
rows,
fill_missing,
\(i, fill_missing) fix_names(data, row_num = i, fill_missing)
) |>
bind_cols() |>
unite(col = "var_names", sep = "") |>
pull(var_names)
data <- data |>
slice(-rows)
names(data) <- col_names_merged
data
}
```
## Fix yishuv id
```{r}
fix_yishuv_id <- function(yishuv_id) {
str_pad(yishuv_id, width = 4, side = "left", pad = "0")
}
```
## Clean yishuv name
```{r}
clean_yishuv_name <- function(yishuv_name) {
yishuv_name |>
str_remove_all("[[:punct:][:symbol:][:digit:]&&[^'\\-()\"]]") |>
str_squish()
}
```
## Replace NAs with other column
```{r}
replace_match <- function(vec, vec_id, match_id, replace_with) {
case_match(
{{ vec_id }},
match_id ~ {{ replace_with }},
.default = vec
)
}
```
## Plot line chart of a statistic by year
```{r}
plot_line_group <- function(data, group, x = year, y = budget_per_capita, legend_labs = waiver()) {
min_x <- min(data |> pull({{ x }}))
max_x <- max(data |> pull({{ x }}))
data |>
mutate({{ group }} := fct_reorder2({{ group }}, {{ x }}, {{ y }})) |>
ggplot(aes({{ x }}, {{ y }}, color = {{ group }}, shape = {{ group }})) +
geom_line(linewidth = 1) +
geom_point(size = 3) +
geom_text(
# data = data |>
# filter(year %in% c(max_x, min_x)),
aes(label = round({{ y }}, digits = 1)),
vjust = -1,
show.legend = FALSE
) +
scale_x_continuous(breaks = min_x:max_x) +
scale_y_continuous(expand = expansion(mult = c(0, 0.1)), limits = c(0, NA)) +
scale_color_discrete(labels = legend_labs) +
scale_shape_discrete(labels = legend_labs) +
theme(
legend.title= element_blank(),
legend.background = element_rect(fill = "white", color = "black")
)
}
```
```{r}
plot_line_group_hypo <- function(data, group, x = year, y = budget_per_capita, is_hypo = type, legend_labs = waiver()) {
min_x <- min(data |> pull({{ x }}))
max_x <- max(data |> pull({{ x }}))
data |>
mutate({{ group }} := fct_reorder2({{ group }}, {{ x }}, {{ y }})) |>
ggplot(aes({{ x }}, {{ y }}, color = {{ group }}, shape = {{ group }}, linetype = {{ is_hypo }})) +
geom_line(linewidth = 1) +
geom_point(size = 3) +
geom_text_repel(
aes(label = if_else( {{ x }} > 2015 | {{ is_hypo }} == "real", as.character(round({{ y }}, digits = 1)), "")),
vjust = -1,
show.legend = FALSE,
direction = "y",
segment.alpha = 0
) +
scale_x_continuous(breaks = min_x:max_x) +
scale_y_continuous(expand = expansion(mult = c(0, 0.1)), limits = c(0, NA)) +
scale_color_discrete(labels = legend_labs) +
scale_shape_discrete(labels = legend_labs) +
scale_linetype_manual(values = c("real" = 1, "hypo" = 3), labels = hypo_labs) +
theme(
legend.title= element_blank(),
legend.background = element_rect(fill = "white", color = "black")
)
}
```
# Municipalities data
## Import a single municipalities file from CBS (2016 and later)
This is a function that gets a path and returns a tibble.
First, it creates a temporary file: it either downloads the file with the path parameter as url, or uses the local path.
later, it reads the two lines of names of variables and handles each one of them separately.
The upper row gets filled with previous variable names for NAs because of merged cells in the original table.
The lower row gets blank string for NAs.
When concatenating, if there is a second argument for the variable, the variable name gets padded with blank space between its two arguments.
Finally, these column names are added to the tibble.
The tibble is read again to ensure good guessing of column types.
```{r}
read_muni_new <- function(path, is_online = FALSE) {
if (is_online)
GET(path, write_disk(path <- tempfile(fileext = get_file_ext(path))))
col_names_merged <- read_excel(path, sheet = 2, skip = 3, n_max = 2, col_names = FALSE) |>
merge_names(names_num = 2, fill_missing = c(TRUE, FALSE)) |>
names()
read_excel(path, sheet = 2, skip = 5, col_names = col_names_merged)
}
df_2018 <- read_muni_new("data/municipalities/2018.xlsx")
```
## Import a single variable from a CBS municipalities file (2016 and later) with a single variable
```{r}
read_muni_new_var <- function(path, var_name, col_num, is_online = FALSE) {
if(is_online)
GET(path, write_disk(path <- tempfile(fileext = get_file_ext(path))))
read_excel(path, sheet = 2, skip = 5, col_names = FALSE) |>
select(
muni_id = 2,
"{var_name}" := all_of(col_num)
)
}
```
## Import a single variable from a CBS municipalities file (2015 and before) with a single variable
This function is important because some SELA data is using population data older than 2018.
This function takes the url of the file, the wanted column numbers for the cities and for the regional councils.
It returns a tibble with a municipality id and the wanted variable values.
```{r}
read_muni_old_var <- function(path, var_name, col_num_1, col_num_2, skip_rows = 1, is_online = FALSE) {
if(is_online)
GET(path, write_disk(path <- tempfile(fileext = get_file_ext(path))))
df1 <- read_excel(path, sheet = 2, skip = skip_rows)
df2 <- read_excel(path, sheet = 4, skip = skip_rows)
df1 <- df1 |>
select(
muni_id = 2,
"{var_name}" := all_of(col_num_1)
) |>
filter(str_length(muni_id) == 4)
df2 <- df2 |>
select(
muni_id = 2,
"{var_name}" := all_of(col_num_2)
) |>
filter(str_length(muni_id) == 2)
bind_rows(df1, df2)
}
```
## Municipality id
Every municipality has different ids for different authorities.
This function reads the requested ids and includes their names if requested.
```{r}
read_muni_id <- function(id_types = c("cbs", "edu", "tax"), include_names = FALSE) {
data <- read_csv("https://raw.githubusercontent.com/matanhakim/general_files/main/muni_ids.csv", col_types = cols(.default = "c"))
if (include_names)
{
data |>
select(contains(id_types))
}
else
{
data |>
select(contains(id_types) & ends_with("id"))
}
}
```
## Yishuvim
This function reads a specific variable from the yishuvim data, alongside its yishuv id.
```{r}
read_yishuv <- function(var_name, col_num) {
read_excel("data/yishuvim/bycode2021.xlsx", col_types = "text") |>
select(
yishuv_id = 2,
"{var_name}" := all_of(col_num)
) |>
mutate(
yishuv_id = fix_yishuv_id(yishuv_id)
)
}
```
This is a specific function that matches yishuv and municipality id.
```{r}
match_yishuv_muni <- function() {
read_yishuv("muni_id", 9) |>
mutate(
muni_id = case_when(
(muni_id == "0" | muni_id == "99") ~ yishuv_id,
TRUE ~ str_pad(muni_id, width = 2, side = "left", pad = "0")
)
)
}
```
This function reads all possible names for yishuvim and their CBS yishuv id.
```{r}
read_yishuv_names <- function() {
read_csv(
"https://raw.githubusercontent.com/matanhakim/general_files/main/yishuv_names.csv",
col_types = cols(.default = "c")
)
}
```
## 2013 CBS SES data
This function reads the 2013 CBS SES data for municipalities that is being used by 2018 SELA regulations to determine eligibility of municipalities.
It reads the file, selects the relevant variables, removes excess rows, and transforms the id to the usual format.
```{r}
read_ses_2013 <- function(url) {
read_excel("data/municipalities/t02.xls", skip = 6) |>
slice(2:256) |>
select(
muni_status = 1,
muni_id = 2,
ses_2013_i = 5,
ses_2013_r = 6,
ses_2013_c = 7
) |>
mutate(
muni_id = as.character(muni_id),
muni_id = case_when(
(muni_status == "0" | muni_status == "99") ~ str_pad(muni_id, width = 4, side = "left", pad = "0"),
TRUE ~ str_pad(muni_status, width = 2, side = "left", pad = "0")
),
across(c(ses_2013_r, ses_2013_c), parse_double)
) |>
select(!muni_status)
}
```
## 2004 CBS periphery data
Important to note that this is and old indicator, therefore since then some municipal jurisdiction changes have happened:
```{r}
read_peri_2004 <- function() {
df <- read_excel("data/indices/24_08_160t2.xls", skip = 7)
df |>
select(
muni_id = 1,
peri_2004_i = 9,
peri_2004_r = 10,
peri_2004_c = 11
) |>
mutate(
muni_id = as.character(muni_id),
muni_id = case_when(
str_length(muni_id) == 5 ~ str_sub(muni_id, start = -2),
TRUE ~ fix_yishuv_id(muni_id)
)
)
}
```
# Elections data
This function reads the raw 2015 elections data file and adds a municipality id for every yishuv.
```{r}
read_elect_muni <- function() {
read_excel("data/elections/results_20.xls") |>
rename(yishuv_id = 2) |>
mutate(yishuv_id = fix_yishuv_id(yishuv_id)) |>
left_join(match_yishuv_muni(), join_by(yishuv_id))
}
```
This function computes voting percentages for Likud and coalition parties in every municipality.
It filters out NA values (like Beduin tribes).
In 2015, there were no voting in Ein Kinya.
```{r}
read_elect_pct <- function() {
read_elect_muni() |>
rename(
pot_votes = 4,
elec_good_votes = 7,
yahadut_hatorah = 9,
habait_hayehudi = 14,
kulanu = 19,
israel_beytenu = 20,
halikud = 21,
shas = 33
) |>
mutate(
coal = yahadut_hatorah +
habait_hayehudi +
kulanu +
israel_beytenu +
halikud +
shas
) |>
group_by(muni_id) |>
summarize(
elec_likud_votes = sum(halikud),
elec_coal_votes = sum(coal),
elec_likud_pct = 100 * sum(halikud) / sum(elec_good_votes),
elec_coal_pct = 100 * sum(coal) / sum(elec_good_votes),
elec_pot_votes = sum(pot_votes),
elec_good_votes = sum(elec_good_votes)
) |>
filter(!is.na(muni_id))
}
```
# Organizations data
## Amutot
This function reads every registered amuta from guidestar and returns its organiztion (tax) id and the name of its registered yishuv
```{r}
read_amutot <- function() {
df_amutot_new <- read_excel("data/organizations/דוח חודשי גיידסטאר.xlsx", sheet = 2) |>
select(
tax_id = 2,
yishuv_name = 14
) |>
mutate(
tax_id = as.character(tax_id),
yishuv_name = clean_yishuv_name(yishuv_name)
)
df_amutot_old <- read_excel("data/organizations/דוח גיידסטאר - אוגוסט 2020.xlsx") |>
select(
tax_id = 2,
yishuv_name = 28
) |>
mutate(
tax_id = as.character(tax_id),
yishuv_name = clean_yishuv_name(yishuv_name)
)
bind_rows(
df_amutot_new,
df_amutot_old
) |>
arrange(tax_id, yishuv_name) |>
distinct(tax_id, .keep_all = TRUE)
}
```
## Companies
```{r}
read_companies <- function() {
read_csv("data/organizations/companies.csv") |>
select(
tax_id = 1,
yishuv_name = 13
) |>
filter(!is.na(yishuv_name)) |>
mutate(
tax_id = as.character(tax_id),
yishuv_name = clean_yishuv_name(yishuv_name)
)
}
```
## Municipalities
```{r}
read_muni_names <- function() {
read_muni_id(include_names = TRUE) |>
select(!c(edu_id, cbs_id)) |>
pivot_longer(!tax_id, names_to = "var", values_to = "yishuv_name") |>
select(!var) |>
distinct(yishuv_name, .keep_all = TRUE)
}
```
## Organiztions with no record
```{r}
read_organizations_bad_names <- function() {
tibble(
tax_id = c(
"589931187", # אוניברסיטת תל אביב
"500701628", # אוניברסיטת חיפה
"580303808", # תזמורת יד חריף (צרעה)
"580503605", # תזמורת נתיה הקאמרית הקיבוצית
"510101819", # חברת נכון בע"מ (חיפה)
"589120880", # המרכז לאמנות יהודית רוסית (תל אביב)
"511854788", # מתנס רמת נגב
"512103383", # תאטרון ענתות (ראשון לציון)
"510021298", # סול בעמ ( לא ידוע)
"501501183", # ועדה מוניציפאלית חברון
"510318652", # מקיצי נרדמים בעמ ( תל אביב)
"510550767", # לאובק חיפה
"500217229", # מגדל תפן
"580409449", # עמותת יוצאי טורקיה בישראל (יהוד-מונוסון)
"510356777", # המכון לתרגום ספרות עברית (תל אביב)
"580270858", # פורום עולים ידידות (חולון)
"510497464", # התאטרון הפתוח בעמ (תל אביב)
"580374270", # אמנות המשחק לתיאטרון ולקולנוע
"580070845", # מרכז זלמן שזר (ירושלים)
"580510097", # להקת המחול מוריה קונג (תל אביב)
"580520229", # אקס טריטוריה (תל אביב)
"580114965", # כת עת אל-שרק (שפרעם)
"580373777", # אנסמבל תיאטרון הרצליה
"500500962", # יד יצחק בן-צבי (ירושלים)
"580302909" # תאיר - מרכז לתרבות יהודית (תל אביב)
),
yishuv_name = c(
"תל אביב - יפו",
"חיפה",
"צרעה",
"נתניה",
"חיפה",
"תל אביב - יפו",
"רמת נגב",
"ראשון לציון",
NA,
"חברון",
"תל אביב - יפו",
"חיפה",
"מגדל תפן",
"יהוד-מונוסון",
"תל אביב - יפו",
"חולון",
"תל אביב - יפו",
"תל אביב - יפו",
"ירושלים",
"תל אביב - יפו",
"תל אביב - יפו",
"שפרעם",
"הרצליה",
"ירושלים",
"תל אביב - יפו"
)
)
}
```
## Match yishuv id to organizations
```{r}
read_organizations <- function() {
bind_rows(
read_amutot(),
read_companies(),
read_muni_names(),
read_organizations_bad_names()
) |>
arrange(tax_id, yishuv_name) |>
distinct(tax_id, .keep_all = TRUE) |>
left_join(read_yishuv_names(), join_by(yishuv_name))
}
```
# Budget data
## Sela
This function reads SELA budget by the ministry of culture from the years 2016-2019.
```{r}
read_sela_budget <- function() {
read_excel("data/budget/תמיכות המשרד לגופי תרבות 2016-2019.xlsx", sheet = 39) |>
slice(-1) |>
select(
tax_id = 1,
# tax_name = 2,
init_2016 = 3,
fest_2016 = 4,
sela_2016 = 5,
init_2017 = 7,
fest_2017 = 8,
sela_2017 = 9,
init_2018 = 11,
fest_2018 = 12,
sela_2018 = 13,
init_2019 = 15,
fest_2019 = 16,
sela_2019 = 17
) |>
pivot_longer(!tax_id, names_to = c("budget_type", "year"), names_sep = "_", values_to = "budget") |>
replace_na(list(budget = 0)) |>
mutate(
year = as.numeric(year)
) |>
pivot_wider(names_from = "budget_type", names_prefix = "budget_approved_", values_from = "budget") |>
left_join(read_muni_id(c("tax", "cbs")), join_by(tax_id)) |>
select(
muni_id = cbs_id,
!tax_id
)
}
```
## Culture (total)
This function reads the raw data from the Open Budget website of the ministry of culture, and summarizes it by year and organization.
```{r}
read_culture_budget <- function() {
read_csv("data/budget/מינהל התרבות__ פירוט כל התמיכות מתקציב זה שאושרו ב כל השנים.csv") |>
select(
tax_id = 6,
year = 7,
budget_approved_culture = 8,
budget_paid_culture = 9
) |>
replace_na(
list(budget_approved_culture = 0, budget_paid_culture = 0)
) |>
mutate(tax_id = as.character(tax_id)) |>
summarise(
.by = c(tax_id, year),
budget_approved_culture = sum(budget_approved_culture),
budget_paid_culture = sum(budget_paid_culture)
)
}
```
This chunk checks which organizations that got budget from the ministry of culture do not appear in the current organizations data.
```{r}
df_culture <- read_culture_budget() |>
left_join(read_organizations(), join_by(tax_id))
df_bad_names <- df_culture |>
filter(is.na(yishuv_id)) |>
distinct(yishuv_name, .keep_all = TRUE)
```
This function matches every organization supported by the ministry of culture with its municipality id. this leaves us with a municipality id for every budget support of the ministry of culture for every organization in every year.
missing values include yishuvim not part of any municipality, like Mikveh Israel and the airport, and budgets that do not go to organiztions, mostly prizes for individuals.
```{r}
add_culture_budget_muni_id <- function() {
df_culture <- read_culture_budget() |>
left_join(read_organizations(), join_by(tax_id)) |>
left_join(match_yishuv_muni(), join_by(yishuv_id)) |>
mutate(
muni_id = case_when(
!is.na(muni_id) ~ muni_id,
str_length(yishuv_id) == 2 ~ yishuv_id
)
)
}
```
This function summarizes the cultural budget data by municipality and year.
```{r}
culture_budget_by_muni <- function() {
add_culture_budget_muni_id() |>
summarise(
.by = c(year, muni_id),
budget_approved_culture = sum(budget_approved_culture),
budget_paid_culture = sum(budget_paid_culture)
)
}
```
# CBS cluster data
## National priority settlements decided by the Israeli government
Since the SELA budget relies also on national priority areas, these data are needed to be imported.
### Getting the list of tables from the national priority webpage
This function reads the table data in the national priority areas government decision webpage, and returns a list of those tables.
```{r}
get_nat_pri_list <- function(){
# nat_pri_url <- "https://www.gov.il/he/departments/policies/2013_des667"
#
# read_html(nat_pri_url) |>
# html_elements("table") |>
# html_table()
list(
read_csv("data/national_priority/nafot_priority.csv", col_names = FALSE),
read_csv("data/national_priority/yishuvim_border.csv"),
read_csv("data/national_priority/yishuvim_priority.csv")
)
}
```
### Merging national priority yishuvim, subdistricts (Nafot) and yishuvim close to the border
This function reads the tables from the previous section and manipulates them: - The nafot (subdistricts) data is added with the corresponding nafa_id column, and converts Hebrew data to logical.
- The yishuvim declared as national priority are cleaned, added with a TRUE column and formats the yishuv_id.
- The yishuvim declared as close to the border or threatened are cleaned, added with a TRUE column and formats the yishuv_id.
- The whole yishuvim list is being called from the CBS website, and then all other three data frames are joined.
NA's are replaced with FALSE, and a final national priority variable for each yishuv is calculated.
- Finally, yishuvim with NA as municipality are filtered out, and a final national priority variable for each municipality is calculated as having either more than 75% of yishuvim in the municipality as national priority, or more than 50% of yishuvim in the municipality as close to the border or threatened.
```{r}
read_nat_pri_munis <- function(){
pri_list <- get_nat_pri_list()
pri_nafot <- pri_list[[1]] |>
add_column(nafa_id = c(29,21,24,62,22,23,71,32,11,61,31,41,44,43,42,51)) |>
mutate(
nafa_id = as.character(nafa_id),
nafa_nat_pri = (X7 == "כן")
) |>
select(nafa_id, nafa_nat_pri)
pri_yishuvim <- pri_list[[2]] |>
select(yishuv_id = 1) |>
slice_tail(n = -1) |>
add_column(yishuv_nat_pri = TRUE) |>
mutate(yishuv_id = fix_yishuv_id(yishuv_id))
pri_border <- pri_list[[3]] |>
select(yishuv_id = 1) |>
slice_tail(n = -1) |>
add_column(border_nat_pri = TRUE) |>
mutate(yishuv_id = fix_yishuv_id(yishuv_id))
pri_df <- match_yishuv_muni() |>
left_join(read_yishuv("nafa_id", 6), join_by(yishuv_id)) |>
left_join(pri_nafot, by = "nafa_id") |>
left_join(pri_yishuvim, by = "yishuv_id") |>
left_join(pri_border, by = "yishuv_id") |>
mutate(
across(ends_with("pri"), \(x) replace_na(x, FALSE)),
is_nat_pri = nafa_nat_pri | yishuv_nat_pri | border_nat_pri
)
pri_df |>
filter(!is.na(muni_id)) |>
group_by(muni_id) |>
summarise(is_nat_pri = (mean(is_nat_pri) > 0.75) | (mean(border_nat_pri) >= 0.5))
}
```
# Create a complete data frame
## Read population for every year
```{r}
df_pop_args_old <- tribble(
~path, ~var_name, ~col_num_1, ~col_num_2, ~skip_rows, ~year,
"", "pop", 15, 30, 0, 2013,
"", "pop", 16, 33, 1, 2014,
"", "pop", 14, 31, 1, 2015
) |>
mutate(
path = str_c("data/municipalities/", year, ".xls")
) |>
select(!year)
df_pop_args_new <- tibble(
path = str_c("data/municipalities/", 2016:2019, ".xlsx"),
var_name = "pop",
col_num = 13
)
df_pop <- bind_rows(
pmap(df_pop_args_old, read_muni_old_var),
pmap(df_pop_args_new, read_muni_new_var)
) |>
mutate(
year = rep(2013:2019, each = 255),
pop = if_else(pop < 1000, pop * 1000, pop)
)
```
## Classify municipalities to sector (Jewish/Arab)
```{r}
df_sector <- read_muni_new_var("data/municipalities/2019.xlsx", "arab_pct", 16) |>
mutate(
arab_pct = as.numeric(str_replace(arab_pct, "-", "0")),
sector = as_factor(if_else(arab_pct > 50, "arab", "jewish"))
) |>
select(!arab_pct)
```
## Read periphery 2015 indices
```{r}
df_peri_2015 <- read_muni_new("data/municipalities/2016.xlsx") |>
select(
muni_id = 2,
muni_type = 4,
peri_2015_c = 187,
peri_2015_i = 188,
peri_2015_r = 189
)
```
## Combine all data frames
```{r}
df <- expand_grid(
year = 2013:2019,
read_muni_id(id_types = "cbs", include_names = TRUE)
) |>
rename(
muni_id = cbs_id,
muni_name = cbs_name
) |>
left_join(culture_budget_by_muni(), join_by(year, muni_id)) |>
left_join(read_sela_budget(), join_by(year, muni_id)) |>
left_join(df_pop, join_by(year, muni_id)) |>
left_join(df_sector, join_by(muni_id)) |>
left_join(read_ses_2013(), join_by(muni_id)) |>
left_join(read_peri_2004(), join_by(muni_id)) |>
left_join(df_peri_2015, join_by(muni_id)) |>
left_join(read_nat_pri_munis(), join_by(muni_id)) |>
left_join(read_elect_pct(), join_by(muni_id))
```
## Recode and add variables
```{r}
na_peri_muni <- c(
"0483", # Bueina
"0628", # Jat
"0490", # Dir ElAssad
"0534", # Osfia
"69", # AlQasum
"68" # Neve Midbar
)
df <- df |>
mutate(
across(contains(c("budget", "elec")), \(x) replace_na(x, 0)),
budget_approved_culture_per_capita = budget_approved_culture / pop,
peri_2004_i = replace_match(peri_2004_i, muni_id, na_peri_muni, peri_2015_i),
peri_2004_r = replace_match(peri_2004_r, muni_id, na_peri_muni, peri_2015_r),
peri_2004_c = replace_match(peri_2004_c, muni_id, na_peri_muni, peri_2015_c)
)
```
# Inequality measures
## Top 10%
```{r}
top_prop <- function(var, weights = 1, top_prop = 0.1) {
tibble(x = var, w = weights) |>
uncount(w) |>
arrange(desc(x)) |>
slice_head(prop = top_prop) |>
summarise(top10_pct = sum(x) / sum(var * weights)) |>
pull(top10_pct)
}
```
## Gini
```{r}
gini_weighted <- function(var, weights) {
tibble(x = var, w = weights) |>
uncount(w) |>
summarise(gini = reldist::gini(x)) |>
pull(gini)
}
```
## Total budget
```{r}
df |>
summarise(
.by = year,
budget_tot = sum(budget_approved_culture),
budget_per_capita = sum(budget_approved_culture) / sum(pop)
) |>
pivot_longer(contains("budget"), names_to = "var", values_to = "value") |>
ggplot(aes(year, value)) +
geom_line() +
geom_point() +
geom_text(
aes(label = if_else(value < 1e6, as.character(round(value, 1)), paste0(round(value / 1e6, 0), "M"))),
vjust = -1
) +
facet_wrap(~ var, scales = "free_y", labeller = labeller(var = c(budget_per_capita = "תקציב מינהל תרבות לתושב", budget_tot = "תקציב מינהל תרבות כולל"))) +
scale_y_continuous(
labels = label_number(scale_cut = cut_short_scale()),
limits = c(0, NA),
expand = expansion(mult = c(0, 0.1))
) +
scale_x_continuous(
breaks = 2013:2019,
labels = 2013:2019,
expand = expansion(mult = c(0.1, 0.1))
) +
theme(
panel.grid.minor.x = element_blank()
) +
labs(
x = "שנה",
y = 'ש"ח'
)
```
## Inequality calculation
```{r}
df_gini <- df |>
summarise(
.by = year,
# gini_1 = acid::weighted.gini(budget_approved_culture_per_capita, w = pop)[[1]],
# gini_2 = dineq::gini.wtd(budget_approved_culture_per_capita, weights = pop),