-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.qmd
More file actions
1758 lines (1480 loc) · 42.7 KB
/
Copy pathindex.qmd
File metadata and controls
1758 lines (1480 loc) · 42.7 KB
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
```{r}
#| label: Setup
#| include: false
library(here)
source(here("R", "_setup.R"))
```
<!-- badges: start -->
[](https://www.repostatus.org/#active)
[](https://doi.org/10.17605/OSF.IO/8J94M)
[](https://www.gnu.org/licenses/gpl-3.0)
[](https://creativecommons.org/licenses/by-nc-sa/4.0/)
<!-- badges: end -->
## Overview
This report provides a reproducible pipeline for processing and analyzing the microdata on nutritional status monitoring in Brazil from the Brazilian Food and Nutrition Surveillance System ([SISVAN](https://sisaps.saude.gov.br/sisvan/)), focusing on the nutritional status of children aged 0–5 years (i.e., younger than 60 months).
If you are working with other age groups, you will need to adapt the code accordingly. We provide some guidance on how to do this along the report.
For instructions on how to run the pipeline, see the repository [README](https://github.com/sustentarea/nutritional-status/blob/main/README.md).
Click [here](https://sustentarea.github.io/nutritional-status-analysis/) to see a report with a longitudinal analysis of the processed data.
## Problem
The Food and Nutrition Surveillance System ([SISVAN](https://sisaps.saude.gov.br/sisvan/)) is a strategic tool for monitoring the nutritional status of the Brazilian population, particularly those served by Brazil's Unified Health System ([SUS](https://www.gov.br/saude/pt-br/sus)). However, despite its broad scope and importance, the anthropometric data recorded in SISVAN often suffer from accessability and quality issues that limit their usefulness for rigorous analyses and evidence-based policymaking [@silva2023a].
Multiple factors contribute to these quality concerns, including the lack of standardized measurement protocols, variability in staff training, inconsistencies in data entry and processing, and incomplete population coverage [@bagni2015; @corsi2017; @perumal2020]. To assess and improve data quality, several indicators have been proposed and applied, such as population coverage [@nascimento2017; @mourao2020], completeness of birth dates and anthropometric measurements [@finaret2018; @nannan2019], digit preference for age, height, and weight [@lyons-amos2017; @bopp2008], the percentage of biologically implausible values [@lawman2015], and the dispersion and distribution of standardized weight and height measurements [@perumal2020; @mei2007].
In light of these challenges, there is a need for an open and reproducible pipeline to process SISVAN microdata. Such a pipeline should facilitate broader access to the data and systematically identify, correct, and remove problematic records, thereby improving the consistency, completeness, and plausibility of the information for research and policymaking.
## Data Availability
::: {style="text-align: left;"}
[](https://doi.org/10.17605/OSF.IO/8J94M)
:::
The processed data are available in [`csv`](https://en.wikipedia.org/wiki/Comma-separated_values), [`rds`](https://rdrr.io/r/base/readRDS.html), and [`parquet`](https://en.wikipedia.org/wiki/Apache_Parquet) formats via a dedicated repository on the Open Science Framework ([OSF](https://osf.io)), accessible [here](https://doi.org/10.17605/OSF.IO/8J94M). Each dataset is accompanied by a metadata file describing its structure and contents.
You can also retrieve these files directly from [R](https://www.r-project.org/) using the [`osfr`](https://docs.ropensci.org/osfr/) package.
## Methods
### Source of Data
The data used in this report come from the following sources:
- Brazilian Food and Nutrition Surveillance System ([SISVAN](https://sisaps.saude.gov.br/sisvan/)):
- Microdata on nutritional status monitoring in Brazil [@sisvana], the primary dataset for this pipeline.
- Brazilian Institute of Geography and Statistics ([IBGE](https://www.ibge.gov.br/)):
- Official codes and metadata for Brazilian municipalities, incorporated via the [`geobr`](https://ipeagit.github.io/geobr/) R package [@pereirab], used to normalize IBGE municipality codes and enrich the analysis with geographic information.
- Department of Informatics of the Brazilian Unified Health System ([DATASUS](https://datasus.saude.gov.br/)):
- Annual population estimates by municipality, age, and sex for Brazil [@datasusb], used to calculate SISVAN's population coverage.
The [DATASUS](https://datasus.saude.gov.br/) population estimates used in this pipeline are processed through a separate reproducible workflow, available [here](https://sustentarea.github.io/population-estimates/) [@vartanian2025b].
### Data Munging
The data munging follow the data science workflow outlined by @wickham2023e, as illustrated in [@fig-wickham-at-al-2023-figure-1]. All processes were made using
the [Quarto](https://quarto.org/) publishing system, along with the [AWK](https://en.wikipedia.org/wiki/AWK) [@aho2023] and [R](https://www.r-project.org/) [@rcoreteama] programming languages, supported by several R packages.
For data manipulation and workflow, priority was given to packages from the [tidyverse](https://www.tidyverse.org/), [rOpenSci](https://ropensci.org/) and [r-spatial](https://r-spatial.org/) ecosystems, as well as other packages adhering to the tidy tools manifesto [@wickham2023c].
::: {#fig-wickham-at-al-2023-figure-1}
{width=75%}
[Source: Reproduced from @wickham2023e.]{.legend}
Data science workflow created by Wickham, Çetinkaya-Runde, and Grolemund.
:::
### Data Validation
::: {.callout-warning}
The validation steps described below are specifically designed for children aged 0–5 years. If you are working with older children or adolescents (ages 5–19 years), you should adapt the code accordingly. For these age groups, we recommend using the WHO's [`anthroplus`](https://CRAN.R-project.org/package=anthroplus) R package [@dirkschumachera].
:::
Different validation techniques were used to ensure data quality and reliability:
- Duplicate records were removed based on unique combinations of the SISVAN identifier (`id`) and assessment date (`date`). Only the latest record for each individual on a given date was retained.
- Weight and height measurements identified as biologically implausible values (BIVs) according to World Health Organization (WHO) child growth standards [@who2006; @who2008] were set to missing. BIVs were detected by calculating z-scores using the [`anthro_zscores`](https://rdrr.io/cran/anthro/man/anthro_zscores.html) function from the WHO [`anthro`](https://CRAN.R-project.org/package=anthro) R package [@dirkschumacher], based on weight, height, age, and sex. Implausible values were flagged when z-scores exceeded established WHO cutoffs (typically $|z| > 5$). For details, see the [function documentation](https://rdrr.io/cran/anthro/man/anthro_zscores.html).
<!-- @silva2023a quality indicators were also used for validation. Refer to the article for more details. -->
### Data Categorization
Nutritional status categories are ideally determined using z-scores, as recommended by the WHO child growth standards [@who2006, Section C]. However, SISVAN data report age only in years, rather than in days or months as required for accurate z-score calculation. This limitation introduces substantial classification error if z-scores are computed directly. Therefore, we use the nutritional status categories already provided in the SISVAN microdata and set these categories to missing when biologically implausible values (BIVs) were identified.
### Code Style
The Tidyverse [Tidy Tools Manifesto](https://tidyverse.tidyverse.org/articles/manifesto.html) [@wickham2023c], [code style guide](https://style.tidyverse.org/) [@wickhamb] and [design principles](https://design.tidyverse.org/) [@wickhamc] were followed to ensure consistency and enhance readability.
### Reproducibility
The pipeline is fully reproducible and can be run again at any time. To ensure consistent results, the [`renv`](https://rstudio.github.io/renv/) package [@usheya] is used to manage and restore the R environment. See the [README](https://github.com/sustentarea/nutritional-status/blob/main/README.md) file in the code repository to learn how to run it.
## Set Environment
### Load Packages
```{r}
#| label: Set the Environment
#| output: false
library(anthro)
library(brandr)
library(cli)
library(dplyr)
library(forcats)
library(fs)
library(geobr)
library(ggplot2)
library(ggspatial)
library(groomr) # github.com/danielvartan/groomr
library(here)
library(htmltools)
library(httr2)
library(janitor)
library(knitr)
library(labelled)
library(lubridate)
library(nanoparquet)
library(orbis) # github.com/danielvartan/orbis
library(osfr)
library(pal) # gitlab.com/rpkg.dev/pal
library(parallel)
library(quartabs)
library(readr)
library(rutils) # github.com/danielvartan/rutils
library(scales)
library(sf)
library(stringr)
library(tidyr)
library(utils)
library(vroom)
library(zip)
```
### Set Data Directories
```{r}
raw_data_dir <- here("data-raw")
data_dir <- here("data")
```
```{r}
for (i in c(raw_data_dir, data_dir)) {
if (!dir_exists(i)) dir_create(i, recurse = TRUE)
}
```
### Set Initial Variables
::: {.callout-note}
The `year` variable represent the year of the consolidated [SISVAN](https://sisaps.saude.gov.br/sisvan/) dataset on nutritional status.
:::
```{r}
year <- 2023
```
::: {.callout-note}
The `age_limits` variable define the age range (in years) of individuals to be included in the analysis.
:::
```{r}
age_limits <- c(0, 4) # == Less than 5 years
```
::: {.callout-note}
The `col_selection` variable specifies the columns to be imported from the raw [SISVAN](https://sisaps.saude.gov.br/sisvan/) microdata files.
Click [here](https://s3.sa-east-1.amazonaws.com/ckan.saude.gov.br/SISVAN/estado_nutricional/Dicion%C3%A1rio+de+Dados+-+Estado+Nutricional.pdf) to access the microdata data dictionary (in Portuguese).
:::
```{r}
col_selection <- c(
"CO_PESSOA_SISVAN",
"DT_ACOMPANHAMENTO",
"CO_MUNICIPIO_IBGE",
"CO_CNES",
"SG_SEXO",
"NU_IDADE_ANO",
"CO_RACA_COR",
"NU_PESO",
"NU_ALTURA",
"PESO X IDADE",
"PESO X ALTURA",
"CRI. ALTURA X IDADE",
"CRI. IMC X IDADE"
)
```
## Download and Import IBGE Municipalities Data
::: {.callout-note}
See the [Source of Data](#source-of-data) section for more information.
:::
```{r}
#| label: Download and Import IBGE Municipalities Data
municipalities_data <- brazil_municipality(year = year)
```
```{r}
municipalities_data |> glimpse()
```
## Download DATASUS Population Estimates
::: {.callout-note}
See the [Source of Data](#source-of-data) section for more information.
:::
### List Files
```{r}
#| label: Download DATASUS Population Estimates
datasus_file_pattern <-
"datasus-population-estimates-" |>
paste0(year)
```
```{r}
datasus_file <-
raw_data_dir |>
here(paste0(datasus_file_pattern, ".rds"))
```
```{r}
osf_raw_data_id <- "h3pyd"
```
```{r}
osf_raw_data_file <-
osf_raw_data_id |>
osf_retrieve_node() |>
osf_ls_files(
type = "file",
pattern = paste0(year, ".rds")
) |>
filter(str_detect(name, paste0("^", year, "\\.rds$")))
```
```{r}
osf_raw_data_file
```
### Download Data
```{r}
osf_raw_data_file |>
osf_download(
path = raw_data_dir,
conflicts = "overwrite"
) |>
pull(local_path)
```
### Rename File
```{r}
if (file_exists(datasus_file)) {
datasus_file |> file_delete()
}
```
```{r}
raw_data_dir |>
dir_ls(
type = "file",
regexp = paste0(year, "\\.rds$")
) |>
file_move(datasus_file)
```
## Import DATASUS Population Estimates
```{r}
#| label: Import DATASUS Population Estimates
population_estimates_data <- datasus_file |> read_rds()
```
```{r}
population_estimates_data |> glimpse()
```
## Download SISVAN Microdata on Nutritional Status
::: {.callout-note}
See the [Source of Data](#source-of-data) section for more information.
:::
::: {.callout-note}
The microdata files are very large. For practical reasons, some code chunks have `eval: false` set to prevent downloading the data each time the report is rendered. When running the pipeline in a loop or for full automation, remove these lines to enable automatic downloading.
:::
### Download Data
```{r}
#| label: Download SISVAN Microdata on Nutritional Status
file <-
"sisvan_estado_nutricional_" |>
paste0(year, ".zip")
```
```{r}
#| eval: false
"https://s3.sa-east-1.amazonaws.com/ckan.saude.gov.br" |>
path(
"SISVAN",
"estado_nutricional",
file
) |>
request() |>
req_progress() |>
req_perform(here(raw_data_dir, file))
```
### Unzip Data
```{r}
#| eval: false
here(raw_data_dir, file) |>
unzip(exdir = raw_data_dir)
```
### Delete Zip Files
```{r}
#| eval: false
raw_data_dir |>
dir_ls(type = "file", regexp = "\\.zip$") |>
file_delete()
```
### Check Data Dimensions
```{r}
file <- file |> str_replace("\\.zip$", "\\.csv")
```
```{r}
raw_data_dir |>
here(file) |>
peek_csv_file(
delim = ";",
skip = 0,
has_header = TRUE
)
```
## Import and Filter Data
::: {.callout-note}
The [`vroom`](https://vroom.r-lib.org/) R package together with the [AWK](https://en.wikipedia.org/wiki/AWK) programming language were use to efficiently handle large datasets and mitigate memory issues. This approach allows the pipeline to run locally on most machines, though we recommend a minimum of 12 GB of RAM for optimal performance. Alternatively, the pipeline can also be executed on cloud platforms such as [Google Colab](https://colab.research.google.com/) and [RStudio Cloud](https://rstudio.cloud/), or using [GitHub Actions](https://docs.github.com/en/actions/concepts/runners/larger-runners) large runners.
:::
### Define Column Names and Schema
```{r}
#| label: Import and Filter Data
col_names <- c(
"CO_ACOMPANHAMENTO",
"CO_PESSOA_SISVAN",
"ST_PARTICIPA_ANDI",
"CO_MUNICIPIO_IBGE",
"SG_UF",
"NO_MUNICIPIO",
"CO_CNES",
"NU_IDADE_ANO",
"NU_FASE_VIDA",
"DS_FASE_VIDA",
"SG_SEXO",
"CO_RACA_COR",
"DS_RACA_COR",
"CO_POVO_COMUNIDADE",
"DS_POVO_COMUNIDADE",
"CO_ESCOLARIDADE",
"DS_ESCOLARIDADE",
"DT_ACOMPANHAMENTO",
"NU_COMPETENCIA",
"NU_PESO",
"NU_ALTURA",
"DS_IMC",
"DS_IMC_PRE_GESTACIONAL",
"PESO X IDADE",
"PESO X ALTURA",
"CRI. ALTURA X IDADE",
"CRI. IMC X IDADE",
"ADO. ALTURA X IDADE",
"ADO. IMC X IDADE",
"CO_ESTADO_NUTRI_ADULTO",
"CO_ESTADO_NUTRI_IDOSO",
"CO_ESTADO_NUTRI_IMC_SEMGEST",
"CO_SISTEMA_ORIGEM_ACOMP",
"SISTEMA_ORIGEM_ACOMP"
)
```
```{r}
#| code-fold: false
schema <- cols(
"CO_ACOMPANHAMENTO" = col_character(),
"CO_PESSOA_SISVAN" = col_character(),
"ST_PARTICIPA_ANDI" = col_character(),
"CO_MUNICIPIO_IBGE" = col_integer(),
"SG_UF" = col_factor(),
"NO_MUNICIPIO" = col_character(),
"CO_CNES" = col_integer(),
"NU_IDADE_ANO" = col_integer(),
"NU_FASE_VIDA" = col_character(), # decimal mark = "." (double)
"DS_FASE_VIDA" = col_factor(),
"SG_SEXO" = col_factor(),
"CO_RACA_COR" = col_character(),
"DS_RACA_COR" = col_factor(),
"CO_POVO_COMUNIDADE" = col_integer(),
"DS_POVO_COMUNIDADE" = col_factor(),
"CO_ESCOLARIDADE" = col_character(),
"DS_ESCOLARIDADE" = col_factor(),
"DT_ACOMPANHAMENTO" = col_date(),
"NU_COMPETENCIA" = col_integer(),
"NU_PESO" = col_double(),
"NU_ALTURA" = col_integer(),
"DS_IMC" = col_double(),
"DS_IMC_PRE_GESTACIONAL" = col_character(), # decimal mark = "." (double)
"PESO X IDADE" = col_factor(),
"PESO X ALTURA" = col_factor(),
"CRI. ALTURA X IDADE" = col_factor(),
"CRI. IMC X IDADE" = col_factor(),
"ADO. ALTURA X IDADE" = col_factor(),
"ADO. IMC X IDADE" = col_factor(),
"CO_ESTADO_NUTRI_ADULTO" = col_factor(),
"CO_ESTADO_NUTRI_IDOSO" = col_factor(),
"CO_ESTADO_NUTRI_IMC_SEMGEST" = col_factor(),
"CO_SISTEMA_ORIGEM_ACOMP" = col_integer(),
"SISTEMA_ORIGEM_ACOMP" = col_factor()
)
```
### Import and Filter Data
::: {.callout-important}
You may see warning messages about failed parsing. These warnings are expected due to minor inconsistencies in the SISVAN raw data and do not affect the overall analysis.
:::
```{r}
#| warning: false
#| code-fold: false
data <-
vroom(
file = pipe(
paste0(
"awk ",
"-F ", # Field separator
"';' ",
"'{", # Program
"if (",
"($8 >= ",
age_limits[1],
")",
" && ",
"($8 <= ",
age_limits[2],
")",
") ",
"{print}",
"}' ",
raw_data_dir |> here(file) # file
)
),
delim = ";",
col_names = col_names,
col_types = schema,
col_select = all_of(col_selection),
na = c("", "NA"),
locale = locale(
date_names = "pt",
date_format = "%d/%m/%Y",
time_format = "%H:%M:%S",
decimal_mark = ",",
grouping_mark = ".",
tz = "America/Sao_Paulo",
encoding = raw_data_dir |>
here(file) |>
guess_encoding() |>
extract2("encoding") |>
magrittr::extract(1)
),
guess_max = 100,
num_threads = detectCores() |>
multiply_by(0.75) |>
floor(),
progress = TRUE
)
```
```{r}
#| warning: false
data |> glimpse()
```
## Tidy Data
### Rename Columns
```{r}
#| label: Tidy Data
data <-
data |>
clean_names() |>
rename(
id = co_pessoa_sisvan,
date = dt_acompanhamento,
municipality_code = co_municipio_ibge,
cnes = co_cnes,
sex = sg_sexo,
age = nu_idade_ano,
ethnicity = co_raca_cor,
weight = nu_peso,
height = nu_altura,
weight_for_age = peso_x_idade,
weight_for_height = peso_x_altura,
height_for_age = cri_altura_x_idade,
bmi_for_age = cri_imc_x_idade
)
```
```{r}
#| code-fold: false
data |> glimpse()
```
### Standardize Columns
```{r}
data <-
data |>
mutate(
sex = sex |>
as.character() |>
case_match(
"F" ~ "Female",
"M" ~ "Male"
) |>
factor(
levels = c("Male", "Female"),
ordered = FALSE
),
ethnicity = ethnicity |>
as.character() |>
case_match(
"01" ~ "White",
"02" ~ "Black",
"03" ~ "Yellow",
"04" ~ "Brown",
"05" ~ "Indigenous"
) |>
factor(
levels = c(
"White",
"Black",
"Yellow",
"Brown",
"Indigenous"
),
ordered = FALSE
),
weight_for_age = weight_for_age |>
as.character() |>
case_match(
"Muito baixo peso para a idade" ~ "Severely underweight",
"Baixo peso para a idade" ~ "Underweight",
"Peso adequado para idade" ~ "Normal",
"Peso elevado para a idade" ~ "High"
) |>
factor(
levels = c(
"Severely underweight",
"Underweight",
"Normal",
"High"
),
ordered = TRUE
),
weight_for_height = weight_for_height |>
as.character() |>
case_match(
"Magreza acentuada" ~ "Severe wasted",
"Magreza" ~ "Wasted",
"Peso Adequado ou Eutrofico" ~ "Normal",
"Risco de sobrepeso" ~ "Possible risk of overweight",
"Sobrepeso" ~ "Overweight",
"Obesidade" ~ "Obese"
) |>
factor(
levels = c(
"Severe wasted",
"Wasted",
"Normal",
"Possible risk of overweight",
"Overweight",
"Obese"
),
ordered = TRUE
),
height_for_age = height_for_age |>
as.character() |>
case_match(
"Muito baixa estatura para idade" ~ "Severely stunted",
"Baixa estatura para idade" ~ "Stunted",
"Estatura adequada para a idade" ~ "Normal"
) |>
factor(
levels = c(
"Severely stunted",
"Stunted",
"Normal"
),
ordered = TRUE
),
bmi_for_age = bmi_for_age |>
as.character() |>
case_match(
"Magreza acentuada" ~ "Severe wasted",
"Magreza" ~ "Wasted",
"Eutrofia" ~ "Normal",
"Risco de sobrepeso" ~ "Possible risk of overweight",
"Sobrepeso" ~ "Overweight",
"Obesidade" ~ "Obese"
) |>
factor(
levels = c(
"Severe wasted",
"Wasted",
"Normal",
"Possible risk of overweight",
"Overweight",
"Obese"
),
ordered = TRUE
)
)
```
```{r}
#| code-fold: false
data |> glimpse()
```
## Transform Data
### Remove Duplicates
```{r}
#| label: Transform Data
#| warning: false
data <-
data |>
arrange(desc(date)) |>
distinct(id, date, .keep_all = TRUE)
```
```{r}
#| warning: false
data |> glimpse()
```
### Remove Biological Implausible Values (BVI)
::: {.callout-note}
See the [Data Validation](#data-validation) section for more information.
:::
```{r}
data <-
data |>
mutate(
z_scores = anthro_zscores(
sex = as.numeric(sex),
age = age * 12,
is_age_in_month = TRUE,
weight = weight,
lenhei = height,
measure = "h"
),
weight = if_else(
(z_scores$fwei == 1) | (z_scores$flen != 1 & z_scores$fwfl == 1),
NA,
weight
),
height = if_else(
z_scores$flen == 1,
NA,
height
),
weight_for_age = if_else(
is.na(weight),
NA,
weight_for_age
),
weight_for_height = if_else(
is.na(weight) | is.na(height),
NA,
weight_for_height
),
height_for_age = if_else(
is.na(height),
NA,
height_for_age
),
bmi_for_age = if_else(
is.na(weight) | is.na(height),
NA,
bmi_for_age
)
) |>
select(-z_scores)
```
```{r}
data |> glimpse()
```
### Fix Municipality Code
```{r}
data <-
data |>
rename(municipality_code_6 = municipality_code) |>
left_join(
municipalities_data |>
mutate(
municipality_code_6 = municipality_code |>
str_sub(1, 6) |>
as.integer()
) |>
select(municipality_code, municipality_code_6),
by = join_by(municipality_code_6)
) |>
select(-municipality_code_6) |>
relocate(municipality_code, .after = date)
```
```{r}
data |> glimpse()
```
### Arrange Data
```{r}
data <-
data |>
arrange(
date,
municipality_code,
cnes,
sex,
age
)
```
```{r}
data |> glimpse()
```
## Create Data Dictionary
### Prepare Metadata
```{r}
#| label: Create Data Dictionary
metadata <-
data |>
`var_label<-`(
list(
id = "Unique identifier for the individual",
date = "Date of the individual's nutritional assessment",
municipality_code = paste0(
"Institute of Geography and Statistics (IBGE) code of the ",
"municipality where the assessment was performed"
),
cnes = paste0(
"National Registry of Health Establishments (CNES) code of the ",
"health facility where the assessment was performed"
),
sex = "Sex of the individual",
age = "Age of the individual in years",
ethnicity = "Self-reported ethnicity/race or color of the individual",
weight = "Weight of the individual in kilograms",
height = "Height of the individual in centimeters",
weight_for_age = paste0(
"Nutritional status classification (children 0–5) based on ",
"weight-for-age"
),
weight_for_height = paste0(
"Nutritional status classification (children 0–5) based on ",
"weight-for-height"
),
height_for_age = paste0(
"Nutritional status classification (children 0–10) based on ",
"height-for-age"
),
bmi_for_age = paste0(
"Nutritional status classification (children 0–10) based on ",
"BMI-for-age"
)
)
) |>
generate_dictionary(details = "full") |>
convert_list_columns_to_character()
```
### Visualize Final Data
```{r}
metadata |> glimpse()
```
```{r}
metadata
```
```{r}
data |> glimpse()
```
```{r}
data
```
## Save Data
::: {.callout-note}
The processed data are available in [`csv`](https://en.wikipedia.org/wiki/Comma-separated_values), [`rds`](https://rdrr.io/r/base/readRDS.html) and [`parquet`](https://en.wikipedia.org/wiki/Apache_Parquet) formats through a dedicated repository on the Open Science Framework ([OSF](https://doi.org/10.17605/OSF.IO/8J94M)). See the [Data Availability](#data-availability) section for more information.
:::
### Write Data
```{r}
#| label: Write Data
valid_file_pattern <-
year |>
paste0(
"-age-limits-",
age_limits[1],
"-",
age_limits[2]
)
```
```{r}
data |>
write_csv(
here(data_dir, paste0(valid_file_pattern, ".csv"))
)
```
```{r}
data |>
write_rds(
here(data_dir, paste0(valid_file_pattern, ".rds"))
)
```
```{r}
data |>
write_parquet(
here(data_dir, paste0(valid_file_pattern, ".parquet"))
)
```
### Write Metadata
```{r}
metadata_file_pattern <-
"metadata-" |>
paste0(
year,
"-age-limits-",
age_limits[1],
"-",
age_limits[2]
)
```
```{r}
metadata |>
write_csv(
here(data_dir, paste0(metadata_file_pattern, ".csv"))
)
```
```{r}
metadata |>
write_rds(
here(data_dir, paste0(metadata_file_pattern, ".rds"))
)
```
```{r}
metadata |>
write_parquet(
here(data_dir, paste0(metadata_file_pattern, ".parquet"))
)
```
<!-- ## Upload the Data to OSF (Optional) -->
<!-- Only repository administrators can upload data to OSF. -->
<!-- To enable uploads, set a `OSF_PAT` environment variable with a valid OSF personal access token. -->
```{r}
#| eval: false
#| include: false
Sys.getenv("OSF_PAT") |> osf_auth()
```
```{r}
#| eval: false
#| include: false
osf_data_id <- "q7m9d"
```
```{r}
#| eval: false
#| include: false
osf_data_id |>
osf_retrieve_node() |>
osf_upload(
path = c(
here(data_dir, paste0(valid_file_pattern, ".csv")),
here(data_dir, paste0(valid_file_pattern, ".rds")),
here(data_dir, paste0(valid_file_pattern, ".parquet")),
here(data_dir, paste0(metadata_file_pattern, ".csv")),
here(data_dir, paste0(metadata_file_pattern, ".rds")),
here(data_dir, paste0(metadata_file_pattern, ".parquet"))
),
conflicts = "overwrite"
)
```
## Explore Data
### Summarize Frequencies
::: {.callout-important}
Some SISVAN data may show discrepancies when compared to official population estimates. For example, the reported number of children under 5 classified as *yellow* in 2023 appears unusually high. If you notice such inconsistencies, check the [SISVAN web reports](https://sisaps.saude.gov.br/sisvan/relatoriopublico/) to confirm before reporting an issue.
:::
```{r}
#| label: Explore Data
#| code-fold: true
vars <- c(
"sex",
"age",
"ethnicity",
"weight_for_age",
"weight_for_height",
"height_for_age",
"bmi_for_age"
)
```
```{r}
#| code-fold: true
panel_tabset_data <- tibble()
for (i in vars) {
table <-
data |>
arrange(desc(.data[[i]])) |>
distinct(id, .data[[i]]) |>
group_by(.data[[i]]) |>