Add files using upload-large-folder tool
Browse files- README.md +490 -0
- data/2013/Core/FAMILYXX.parquet +3 -0
- data/2013/Core/HOUSEHLD.parquet +3 -0
- data/2013/Core/PERSONSX.parquet +3 -0
- data/2013/Core/SAMADULT.parquet +3 -0
- data/2013/Core/SAMCHILD.parquet +3 -0
- data/2013/Dictionary/VALUES.parquet +3 -0
- data/2013/Dictionary/VARIABLES.parquet +3 -0
- data/2013/ImputedIncome/INCMIMP1.parquet +3 -0
- data/2013/ImputedIncome/INCMIMP2.parquet +3 -0
- data/2013/ImputedIncome/INCMIMP3.parquet +3 -0
- data/2013/ImputedIncome/INCMIMP4.parquet +3 -0
- data/2013/ImputedIncome/INCMIMP5.parquet +3 -0
- data/2013/Injury/INJPOIEP.parquet +3 -0
- data/2013/Mortality/NHIS_2013_MORT_2019_PUBLIC.parquet +3 -0
- data/2013/Paradata/PARADATA.parquet +3 -0
- data/2013/Supplement/FMLYDISB.parquet +3 -0
- data/2013/Supplement/FUNCDISB.parquet +3 -0
- data/2014/Core/FAMILYXX.parquet +3 -0
- data/2014/Core/HOUSEHLD.parquet +3 -0
- data/2014/Core/PERSONSX.parquet +3 -0
- data/2014/Core/SAMADULT.parquet +3 -0
- data/2014/Dictionary/VALUES.parquet +3 -0
- data/2014/Dictionary/VARIABLES.parquet +3 -0
- data/2014/ImputedIncome/INCMIMP1.parquet +3 -0
- data/2014/ImputedIncome/INCMIMP2.parquet +3 -0
- data/2014/ImputedIncome/INCMIMP3.parquet +3 -0
- data/2014/ImputedIncome/INCMIMP4.parquet +3 -0
- data/2014/ImputedIncome/INCMIMP5.parquet +3 -0
- data/2014/Injury/INJPOIEP.parquet +3 -0
- data/2014/Mortality/NHIS_2014_MORT_2019_PUBLIC.parquet +3 -0
- data/2014/Paradata/PARADATA.parquet +3 -0
- data/2014/Supplement/FMLYDISB.parquet +3 -0
- data/2014/Supplement/FUNCDISB.parquet +3 -0
- metadata/VALIDATION.parquet +3 -0
- pipeline/00_config.R +132 -0
- pipeline/01_catalog.R +64 -0
- pipeline/02_download.R +25 -0
- pipeline/03_convert.R +152 -0
- pipeline/04_dictionary.R +232 -0
- pipeline/05_validate.R +346 -0
- pipeline/06_manifest.R +182 -0
- pipeline/07_upload.py +88 -0
- pipeline/catalog_ftp_listing.csv +0 -0
- pipeline/codebook_pdf.R +293 -0
- pipeline/files_spec.R +202 -0
- pipeline/hf_configs.yaml +191 -0
- pipeline/hf_dataset_card_body.md +276 -0
- pipeline/readers.R +111 -0
- pipeline/sas_setup.R +230 -0
README.md
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc0-1.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
pretty_name: NHIS 1997-2025 (Parquet, dictionaries, linked mortality)
|
| 6 |
+
tags:
|
| 7 |
+
- nhis
|
| 8 |
+
- cdc
|
| 9 |
+
- nchs
|
| 10 |
+
- health
|
| 11 |
+
- epidemiology
|
| 12 |
+
- survey
|
| 13 |
+
- public-health
|
| 14 |
+
- mortality
|
| 15 |
+
- parquet
|
| 16 |
+
- duckdb
|
| 17 |
+
size_categories:
|
| 18 |
+
- 10M<n<100M
|
| 19 |
+
task_categories:
|
| 20 |
+
- tabular-classification
|
| 21 |
+
- tabular-regression
|
| 22 |
+
configs:
|
| 23 |
+
- config_name: files
|
| 24 |
+
data_files:
|
| 25 |
+
- split: all
|
| 26 |
+
path: metadata/FILES.parquet
|
| 27 |
+
- config_name: years
|
| 28 |
+
data_files:
|
| 29 |
+
- split: all
|
| 30 |
+
path: metadata/YEARS.parquet
|
| 31 |
+
- config_name: dictionary_variables
|
| 32 |
+
data_files:
|
| 33 |
+
- split: year_1997
|
| 34 |
+
path: data/1997/Dictionary/VARIABLES.parquet
|
| 35 |
+
- split: year_1998
|
| 36 |
+
path: data/1998/Dictionary/VARIABLES.parquet
|
| 37 |
+
- split: year_1999
|
| 38 |
+
path: data/1999/Dictionary/VARIABLES.parquet
|
| 39 |
+
- split: year_2000
|
| 40 |
+
path: data/2000/Dictionary/VARIABLES.parquet
|
| 41 |
+
- split: year_2001
|
| 42 |
+
path: data/2001/Dictionary/VARIABLES.parquet
|
| 43 |
+
- split: year_2002
|
| 44 |
+
path: data/2002/Dictionary/VARIABLES.parquet
|
| 45 |
+
- split: year_2003
|
| 46 |
+
path: data/2003/Dictionary/VARIABLES.parquet
|
| 47 |
+
- split: year_2004
|
| 48 |
+
path: data/2004/Dictionary/VARIABLES.parquet
|
| 49 |
+
- split: year_2005
|
| 50 |
+
path: data/2005/Dictionary/VARIABLES.parquet
|
| 51 |
+
- split: year_2006
|
| 52 |
+
path: data/2006/Dictionary/VARIABLES.parquet
|
| 53 |
+
- split: year_2007
|
| 54 |
+
path: data/2007/Dictionary/VARIABLES.parquet
|
| 55 |
+
- split: year_2008
|
| 56 |
+
path: data/2008/Dictionary/VARIABLES.parquet
|
| 57 |
+
- split: year_2009
|
| 58 |
+
path: data/2009/Dictionary/VARIABLES.parquet
|
| 59 |
+
- split: year_2010
|
| 60 |
+
path: data/2010/Dictionary/VARIABLES.parquet
|
| 61 |
+
- split: year_2011
|
| 62 |
+
path: data/2011/Dictionary/VARIABLES.parquet
|
| 63 |
+
- split: year_2012
|
| 64 |
+
path: data/2012/Dictionary/VARIABLES.parquet
|
| 65 |
+
- split: year_2013
|
| 66 |
+
path: data/2013/Dictionary/VARIABLES.parquet
|
| 67 |
+
- split: year_2014
|
| 68 |
+
path: data/2014/Dictionary/VARIABLES.parquet
|
| 69 |
+
- split: year_2015
|
| 70 |
+
path: data/2015/Dictionary/VARIABLES.parquet
|
| 71 |
+
- split: year_2016
|
| 72 |
+
path: data/2016/Dictionary/VARIABLES.parquet
|
| 73 |
+
- split: year_2017
|
| 74 |
+
path: data/2017/Dictionary/VARIABLES.parquet
|
| 75 |
+
- split: year_2018
|
| 76 |
+
path: data/2018/Dictionary/VARIABLES.parquet
|
| 77 |
+
- split: year_2019
|
| 78 |
+
path: data/2019/Dictionary/VARIABLES.parquet
|
| 79 |
+
- split: year_2020
|
| 80 |
+
path: data/2020/Dictionary/VARIABLES.parquet
|
| 81 |
+
- split: year_2021
|
| 82 |
+
path: data/2021/Dictionary/VARIABLES.parquet
|
| 83 |
+
- split: year_2022
|
| 84 |
+
path: data/2022/Dictionary/VARIABLES.parquet
|
| 85 |
+
- split: year_2023
|
| 86 |
+
path: data/2023/Dictionary/VARIABLES.parquet
|
| 87 |
+
- split: year_2024
|
| 88 |
+
path: data/2024/Dictionary/VARIABLES.parquet
|
| 89 |
+
- split: year_2025
|
| 90 |
+
path: data/2025/Dictionary/VARIABLES.parquet
|
| 91 |
+
- config_name: dictionary_values
|
| 92 |
+
data_files:
|
| 93 |
+
- split: year_1997
|
| 94 |
+
path: data/1997/Dictionary/VALUES.parquet
|
| 95 |
+
- split: year_1998
|
| 96 |
+
path: data/1998/Dictionary/VALUES.parquet
|
| 97 |
+
- split: year_1999
|
| 98 |
+
path: data/1999/Dictionary/VALUES.parquet
|
| 99 |
+
- split: year_2000
|
| 100 |
+
path: data/2000/Dictionary/VALUES.parquet
|
| 101 |
+
- split: year_2001
|
| 102 |
+
path: data/2001/Dictionary/VALUES.parquet
|
| 103 |
+
- split: year_2002
|
| 104 |
+
path: data/2002/Dictionary/VALUES.parquet
|
| 105 |
+
- split: year_2003
|
| 106 |
+
path: data/2003/Dictionary/VALUES.parquet
|
| 107 |
+
- split: year_2004
|
| 108 |
+
path: data/2004/Dictionary/VALUES.parquet
|
| 109 |
+
- split: year_2005
|
| 110 |
+
path: data/2005/Dictionary/VALUES.parquet
|
| 111 |
+
- split: year_2006
|
| 112 |
+
path: data/2006/Dictionary/VALUES.parquet
|
| 113 |
+
- split: year_2007
|
| 114 |
+
path: data/2007/Dictionary/VALUES.parquet
|
| 115 |
+
- split: year_2008
|
| 116 |
+
path: data/2008/Dictionary/VALUES.parquet
|
| 117 |
+
- split: year_2009
|
| 118 |
+
path: data/2009/Dictionary/VALUES.parquet
|
| 119 |
+
- split: year_2010
|
| 120 |
+
path: data/2010/Dictionary/VALUES.parquet
|
| 121 |
+
- split: year_2011
|
| 122 |
+
path: data/2011/Dictionary/VALUES.parquet
|
| 123 |
+
- split: year_2012
|
| 124 |
+
path: data/2012/Dictionary/VALUES.parquet
|
| 125 |
+
- split: year_2013
|
| 126 |
+
path: data/2013/Dictionary/VALUES.parquet
|
| 127 |
+
- split: year_2014
|
| 128 |
+
path: data/2014/Dictionary/VALUES.parquet
|
| 129 |
+
- split: year_2015
|
| 130 |
+
path: data/2015/Dictionary/VALUES.parquet
|
| 131 |
+
- split: year_2016
|
| 132 |
+
path: data/2016/Dictionary/VALUES.parquet
|
| 133 |
+
- split: year_2017
|
| 134 |
+
path: data/2017/Dictionary/VALUES.parquet
|
| 135 |
+
- split: year_2018
|
| 136 |
+
path: data/2018/Dictionary/VALUES.parquet
|
| 137 |
+
- split: year_2019
|
| 138 |
+
path: data/2019/Dictionary/VALUES.parquet
|
| 139 |
+
- split: year_2020
|
| 140 |
+
path: data/2020/Dictionary/VALUES.parquet
|
| 141 |
+
- split: year_2021
|
| 142 |
+
path: data/2021/Dictionary/VALUES.parquet
|
| 143 |
+
- split: year_2022
|
| 144 |
+
path: data/2022/Dictionary/VALUES.parquet
|
| 145 |
+
- split: year_2023
|
| 146 |
+
path: data/2023/Dictionary/VALUES.parquet
|
| 147 |
+
- split: year_2024
|
| 148 |
+
path: data/2024/Dictionary/VALUES.parquet
|
| 149 |
+
- split: year_2025
|
| 150 |
+
path: data/2025/Dictionary/VALUES.parquet
|
| 151 |
+
- config_name: linked_mortality
|
| 152 |
+
data_files:
|
| 153 |
+
- split: year_1997
|
| 154 |
+
path: data/1997/Mortality/NHIS_1997_MORT_2019_PUBLIC.parquet
|
| 155 |
+
- split: year_1998
|
| 156 |
+
path: data/1998/Mortality/NHIS_1998_MORT_2019_PUBLIC.parquet
|
| 157 |
+
- split: year_1999
|
| 158 |
+
path: data/1999/Mortality/NHIS_1999_MORT_2019_PUBLIC.parquet
|
| 159 |
+
- split: year_2000
|
| 160 |
+
path: data/2000/Mortality/NHIS_2000_MORT_2019_PUBLIC.parquet
|
| 161 |
+
- split: year_2001
|
| 162 |
+
path: data/2001/Mortality/NHIS_2001_MORT_2019_PUBLIC.parquet
|
| 163 |
+
- split: year_2002
|
| 164 |
+
path: data/2002/Mortality/NHIS_2002_MORT_2019_PUBLIC.parquet
|
| 165 |
+
- split: year_2003
|
| 166 |
+
path: data/2003/Mortality/NHIS_2003_MORT_2019_PUBLIC.parquet
|
| 167 |
+
- split: year_2004
|
| 168 |
+
path: data/2004/Mortality/NHIS_2004_MORT_2019_PUBLIC.parquet
|
| 169 |
+
- split: year_2005
|
| 170 |
+
path: data/2005/Mortality/NHIS_2005_MORT_2019_PUBLIC.parquet
|
| 171 |
+
- split: year_2006
|
| 172 |
+
path: data/2006/Mortality/NHIS_2006_MORT_2019_PUBLIC.parquet
|
| 173 |
+
- split: year_2007
|
| 174 |
+
path: data/2007/Mortality/NHIS_2007_MORT_2019_PUBLIC.parquet
|
| 175 |
+
- split: year_2008
|
| 176 |
+
path: data/2008/Mortality/NHIS_2008_MORT_2019_PUBLIC.parquet
|
| 177 |
+
- split: year_2009
|
| 178 |
+
path: data/2009/Mortality/NHIS_2009_MORT_2019_PUBLIC.parquet
|
| 179 |
+
- split: year_2010
|
| 180 |
+
path: data/2010/Mortality/NHIS_2010_MORT_2019_PUBLIC.parquet
|
| 181 |
+
- split: year_2011
|
| 182 |
+
path: data/2011/Mortality/NHIS_2011_MORT_2019_PUBLIC.parquet
|
| 183 |
+
- split: year_2012
|
| 184 |
+
path: data/2012/Mortality/NHIS_2012_MORT_2019_PUBLIC.parquet
|
| 185 |
+
- split: year_2013
|
| 186 |
+
path: data/2013/Mortality/NHIS_2013_MORT_2019_PUBLIC.parquet
|
| 187 |
+
- split: year_2014
|
| 188 |
+
path: data/2014/Mortality/NHIS_2014_MORT_2019_PUBLIC.parquet
|
| 189 |
+
- split: year_2015
|
| 190 |
+
path: data/2015/Mortality/NHIS_2015_MORT_2019_PUBLIC.parquet
|
| 191 |
+
- split: year_2016
|
| 192 |
+
path: data/2016/Mortality/NHIS_2016_MORT_2019_PUBLIC.parquet
|
| 193 |
+
- split: year_2017
|
| 194 |
+
path: data/2017/Mortality/NHIS_2017_MORT_2019_PUBLIC.parquet
|
| 195 |
+
- split: year_2018
|
| 196 |
+
path: data/2018/Mortality/NHIS_2018_MORT_2019_PUBLIC.parquet
|
| 197 |
+
- config_name: pair_weights
|
| 198 |
+
data_files:
|
| 199 |
+
- split: year_2019
|
| 200 |
+
path: data/2019/Design/FINAL_PAIR_WEIGHT2019.parquet
|
| 201 |
+
- split: year_2020
|
| 202 |
+
path: data/2020/Design/FINAL_PAIR_WEIGHT2020.parquet
|
| 203 |
+
- split: year_2021
|
| 204 |
+
path: data/2021/Design/FINAL_PAIR_WEIGHT2021.parquet
|
| 205 |
+
- split: year_2022
|
| 206 |
+
path: data/2022/Design/FINAL_PAIR_WEIGHT2022.parquet
|
| 207 |
+
- split: year_2023
|
| 208 |
+
path: data/2023/Design/FINAL_PAIR_WEIGHT2023.parquet
|
| 209 |
+
- split: year_2024
|
| 210 |
+
path: data/2024/Design/FINAL_PAIR_WEIGHT2024.parquet
|
| 211 |
+
- split: year_2025
|
| 212 |
+
path: data/2025/Design/FINAL_PAIR_WEIGHT2025.parquet
|
| 213 |
+
---
|
| 214 |
+
|
| 215 |
+
# NHIS 1997–2025 in Parquet (with dictionaries and linked mortality)
|
| 216 |
+
|
| 217 |
+
This dataset contains the public-use data files of the U.S. **National Health Interview Survey
|
| 218 |
+
(NHIS)** of the National Center for Health Statistics (NCHS), survey years **1997 through 2025**,
|
| 219 |
+
converted to Parquet: one Parquet file per original NCHS data file, under the NCHS file name.
|
| 220 |
+
It also includes:
|
| 221 |
+
|
| 222 |
+
- a **variable dictionary for each survey year**, built from the NCHS SAS input programs (column
|
| 223 |
+
positions, labels, value formats) and the NCHS codebooks (question text, universe, published
|
| 224 |
+
frequencies), with the observed count of every coded value;
|
| 225 |
+
- the **NCHS public-use linked mortality files** for NHIS 1997–2018 (follow-up through
|
| 226 |
+
31 December 2019);
|
| 227 |
+
- the imputed income files, paradata, supplements, injury/poisoning episode files, revised and
|
| 228 |
+
parent–child pair weights, and the NCHS dummy records for singleton PSUs.
|
| 229 |
+
|
| 230 |
+
Note on 2016: NCHS revised the 2016 weights in 2017. The 2016 ASCII files used here already carry
|
| 231 |
+
the revised weights (they equal the separately published `*_REVWTS` files, which are included as
|
| 232 |
+
published).
|
| 233 |
+
|
| 234 |
+
Built for the Bioanalysis R package. It works equally well with any tool that reads Parquet:
|
| 235 |
+
DuckDB, Arrow, Polars, pandas or R.
|
| 236 |
+
|
| 237 |
+
| | |
|
| 238 |
+
|---|---|
|
| 239 |
+
| Years | 29 (1997–2018 original design, 2019–2025 redesigned questionnaire) |
|
| 240 |
+
| Files | 457 Parquet data files plus 2 × 29 dictionary files |
|
| 241 |
+
| Rows | 28.2 million (0.37 GB of Parquet) |
|
| 242 |
+
| Persons (1997–2018 PERSONSX) | 2,061,980 |
|
| 243 |
+
| Sample adults (1997–2025) | 878,760 |
|
| 244 |
+
| Sample children (1997–2025) | 313,708 |
|
| 245 |
+
| Values | Original public-use codes; nothing recoded, imputed or dropped |
|
| 246 |
+
|
| 247 |
+
## Layout
|
| 248 |
+
|
| 249 |
+
```
|
| 250 |
+
data/<year>/<component>/<FILE>.parquet
|
| 251 |
+
data/<year>/Dictionary/VARIABLES.parquet one row per file x variable
|
| 252 |
+
data/<year>/Dictionary/VALUES.parquet one row per file x variable x code
|
| 253 |
+
metadata/FILES.parquet every file: rows, columns, grain, join keys, design variables, source URL, MD5
|
| 254 |
+
metadata/YEARS.parquet every year: design period, sample sizes, strata/PSU/weights, pooling guidance
|
| 255 |
+
metadata/VALIDATION.parquet every validation check: expected, observed, source
|
| 256 |
+
pipeline/ the R scripts that rebuilt everything from the NCHS sources
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
`<year>` is the survey year (`1997` … `2025`). File names are the NCHS data file names in upper case
|
| 260 |
+
(`PERSONSX`, `SAMADULT`, `ADULT19`, `CHILDINC24`, `INCMIMP3`, `NHIS_2010_MORT_2019_PUBLIC`, …).
|
| 261 |
+
`<component>` groups the NCHS file types:
|
| 262 |
+
|
| 263 |
+
| Component | NCHS files |
|
| 264 |
+
|---|---|
|
| 265 |
+
| `Core` | 1997–2018: `HOUSEHLD`, `FAMILYXX`, `PERSONSX`, `SAMADULT`, `SAMCHILD`; 2019+: `ADULTyy`, `CHILDyy` |
|
| 266 |
+
| `Supplement` | `IMMUNIZE` (1997–2003), `PREGSMKG`, `PREVADLT`, `PREVCHLD` (1998), `ALTHEALT`/`ALTVERBT` (2002), `ALTHEALT`/`CHILDCAM` (2007, 2012), `CANCERXX` (2005, 2010, 2015), `DISBTEST` (2009–2010), `QUALLIFE` (2010), `ADLTDISB`/`CHLDDISB` (2011–2012), `FMLYDISB`/`FUNCDISB` (2011–2017), `SC_BWTyy` (sample child birth weight, 2004–2010), `RATCAT07` (corrected 2007 poverty ratio) |
|
| 267 |
+
| `Injury` | `INJEPSOD`, `POIEPSOD` (1997–1999), `INJPOIEP` (2000–2017), `INJVERBT` (1997–2010) |
|
| 268 |
+
| `ImputedIncome` | `INCMIMP1`–`5` (1997–2018; `INCMAP1`–`5` in 2003–2004), `INCIMPS1`–`5` (top-coded supplemental files, 1997–2008), `ADULTINCyy`, `CHILDINCyy` (2019+, ten implicates stacked: `IMPNUM` in 2019–2020, `IMPNUM_A` / `IMPNUM_C` from 2021) |
|
| 269 |
+
| `Paradata` | `PARADATA` (2006–2018), `PARADATAyy` (2019+) |
|
| 270 |
+
| `Longitudinal` | `ADULTLONG20` (2019–2020 longitudinal weight `WTSA_L`), `ADULTPART20` (pooled 2019–2020 weight `WTSA_P`) |
|
| 271 |
+
| `Design` | `FINAL_PAIR_WEIGHTyyyy` (parent–child pair weights, 2019+), `*_REVWTS` (revised 2016 weights), `SAD_WGTS` (2010 Sample Adult × disability tests weight), `2003SAMCHILD`, `2005SAMCHILD`, `2007SAMCHILD`, `2007CHILDCAM` (NCHS dummy records for singleton PSUs, weight 1) |
|
| 272 |
+
| `Mortality` | `NHIS_<year>_MORT_2019_PUBLIC` (1997–2018) |
|
| 273 |
+
|
| 274 |
+
## Joining
|
| 275 |
+
|
| 276 |
+
**Within a year, 1997–2018.** Records are identified hierarchically:
|
| 277 |
+
|
| 278 |
+
- household: `HHX`;
|
| 279 |
+
- family: `HHX` + `FMX`;
|
| 280 |
+
- person: `HHX` + `FMX` + `FPX` (the person number is called `PX` in 1997–2003 files and in the
|
| 281 |
+
1997–2003 imputed income files; rename it to `FPX` to stack years);
|
| 282 |
+
- episode files add the episode number: `INJEPNO` / `POIEPNO` (1997–1999), `IPEPNO` (2000+);
|
| 283 |
+
- `IMMUNIZE` adds `IMRESPNO`; the imputed income files hold one implicate each (`IMPNUM`);
|
| 284 |
+
- the 2009 `DISBTEST` file spans the 2008 and 2009 interviews: its key includes `SRVY_YR`.
|
| 285 |
+
|
| 286 |
+
So `PERSONSX`, `SAMADULT`, `SAMCHILD`, the person-level supplements and `INCMIMPn` join on
|
| 287 |
+
`HHX + FMX + FPX` (or `PX`); `FAMILYXX` joins on `HHX + FMX`; `HOUSEHLD` on `HHX`. `HHX` is only
|
| 288 |
+
unique within a year: always join within a year (or include `SRVY_YR` in the key when stacking).
|
| 289 |
+
|
| 290 |
+
**Within a year, 2019+.** There is one sample adult and at most one sample child per household,
|
| 291 |
+
so every file joins on `HHX`. `ADULTINCyy` / `CHILDINCyy` have ten rows per `HHX` (one per
|
| 292 |
+
implicate: `IMPNUM` in 2019–2020, `IMPNUM_A` / `IMPNUM_C` from 2021; from 2021 the `ADULTyy` /
|
| 293 |
+
`CHILDyy` files also carry an `IMPNUM_A` / `IMPNUM_C` column, see the NCHS imputation
|
| 294 |
+
documentation). `FINAL_PAIR_WEIGHTyyyy` joins on `HHX`. `ADULTPART20` and
|
| 295 |
+
`ADULTLONG20` use `HHX_2020` (= `HHX` of `ADULT20`) and `ADULTLONG20` also carries `HHX_2019`
|
| 296 |
+
(= `HHX` of `ADULT19`): this is the only cross-year identity in the public files.
|
| 297 |
+
|
| 298 |
+
**Linked mortality.** The mortality files identify people by `PUBLICID`, a 14-character string that
|
| 299 |
+
NCHS builds as `SRVY_YR` (4) + `HHX` (6) + `FMX` (2) + `FPX` (2) of the 1997–2018 person files.
|
| 300 |
+
Values are kept as published, so join with
|
| 301 |
+
`substr(PUBLICID,1,4) = SRVY_YR, substr(PUBLICID,5,6) = HHX, substr(PUBLICID,11,2) = FMX,
|
| 302 |
+
substr(PUBLICID,13,2) = FPX` (or `PX` for 1997–2003). Mortality follow-up covers adults 18+
|
| 303 |
+
(`ELIGSTAT = 1` eligible); use `WGT_NEW` (person) or `SA_WGT_NEW` (sample adult), the weights NCHS
|
| 304 |
+
adjusted for ineligible records. The 1997–2014 files list every person of `PERSONSX`; the 2015–2018
|
| 305 |
+
files list sample adults and sample children only.
|
| 306 |
+
|
| 307 |
+
`metadata/FILES.parquet` gives the `grain` (checked on the data: one row per key, or several) and
|
| 308 |
+
`join_keys` of every file.
|
| 309 |
+
|
| 310 |
+
## Quick start
|
| 311 |
+
|
| 312 |
+
DuckDB (Python, R or CLI). No download is needed:
|
| 313 |
+
|
| 314 |
+
```python
|
| 315 |
+
import duckdb
|
| 316 |
+
con = duckdb.connect()
|
| 317 |
+
base = "hf://datasets/jamesjiadazhan/NHIS/data"
|
| 318 |
+
con.sql(f"""
|
| 319 |
+
SELECT a.HHX, a.AGEP_A, a.SEX_A, a.SMKCIGST_A, a.WTFA_A, a.PSTRAT, a.PPSU, i.FAMINCTC_A
|
| 320 |
+
FROM read_parquet('{base}/2019/Core/ADULT19.parquet') a
|
| 321 |
+
LEFT JOIN (SELECT * FROM read_parquet('{base}/2019/ImputedIncome/ADULTINC19.parquet')
|
| 322 |
+
WHERE IMPNUM = 1) i USING (HHX)
|
| 323 |
+
""").df()
|
| 324 |
+
```
|
| 325 |
+
|
| 326 |
+
1997–2018 person + sample adult + mortality:
|
| 327 |
+
|
| 328 |
+
```python
|
| 329 |
+
con.sql(f"""
|
| 330 |
+
SELECT s.HHX, s.FMX, s.FPX, s.AGE_P, s.SEX, s.WTFA_SA, s.STRAT_P, s.PSU_P,
|
| 331 |
+
m.ELIGSTAT, m.MORTSTAT, m.UCOD_LEADING, m.DODYEAR, m.SA_WGT_NEW
|
| 332 |
+
FROM read_parquet('{base}/2010/Core/SAMADULT.parquet') s
|
| 333 |
+
LEFT JOIN read_parquet('{base}/2010/Mortality/NHIS_2010_MORT_2019_PUBLIC.parquet') m
|
| 334 |
+
ON m.PUBLICID = CAST(s.SRVY_YR AS VARCHAR) || s.HHX || s.FMX || s.FPX
|
| 335 |
+
""").df()
|
| 336 |
+
```
|
| 337 |
+
|
| 338 |
+
Dictionary lookup:
|
| 339 |
+
|
| 340 |
+
```python
|
| 341 |
+
con.sql(f"""
|
| 342 |
+
SELECT file, variable, label, question_text, universe
|
| 343 |
+
FROM read_parquet('{base}/2019/Dictionary/VARIABLES.parquet')
|
| 344 |
+
WHERE lower(label) LIKE '%cigarette%'
|
| 345 |
+
""").show()
|
| 346 |
+
con.sql(f"""
|
| 347 |
+
SELECT code, description, count_data, count_published
|
| 348 |
+
FROM read_parquet('{base}/2019/Dictionary/VALUES.parquet')
|
| 349 |
+
WHERE file = 'ADULT19' AND variable = 'SMKCIGST_A'
|
| 350 |
+
""").show()
|
| 351 |
+
```
|
| 352 |
+
|
| 353 |
+
R (arrow):
|
| 354 |
+
|
| 355 |
+
```r
|
| 356 |
+
library(arrow)
|
| 357 |
+
base <- "https://huggingface.co/datasets/jamesjiadazhan/NHIS/resolve/main/data"
|
| 358 |
+
adult <- read_parquet(file.path(base, "2019/Core/ADULT19.parquet"))
|
| 359 |
+
```
|
| 360 |
+
|
| 361 |
+
Hugging Face `datasets` (the configs listed above: dictionaries, linked mortality and pair weights,
|
| 362 |
+
each split by year):
|
| 363 |
+
|
| 364 |
+
```python
|
| 365 |
+
from datasets import load_dataset
|
| 366 |
+
mort = load_dataset("jamesjiadazhan/NHIS", "linked_mortality", split="year_2010")
|
| 367 |
+
```
|
| 368 |
+
|
| 369 |
+
## Survey design: required for every NHIS estimate
|
| 370 |
+
|
| 371 |
+
NHIS is a multistage area probability sample. Every estimate must use the weights and the public-use
|
| 372 |
+
design variables (Taylor linearization, PSUs treated as sampled with replacement, as NCHS
|
| 373 |
+
documents). `metadata/YEARS.parquet` lists them for every year:
|
| 374 |
+
|
| 375 |
+
| Years | Strata | PSU | Weights |
|
| 376 |
+
|---|---|---|---|
|
| 377 |
+
| 1997–2005 | `STRATUM` | `PSU` | `WTFA_HH` (household), `WTFA_FAM` (family), `WTFA` (person), `WTFA_SA` (sample adult), `WTFA_SC` (sample child), supplement-specific weights |
|
| 378 |
+
| 2006–2015 | `STRAT_P` | `PSU_P` | as above |
|
| 379 |
+
| 2016–2018 | `PSTRAT` | `PPSU` | as above |
|
| 380 |
+
| 2019–2025 | `PSTRAT` | `PPSU` | `WTFA_A` (sample adult), `WTFA_C` (sample child); 2019 also `WTIA_A`/`WTIA_C`; 2020 `WTSA_P`, `WTSA_L`; `final_pair_weight` (parent–child pairs) |
|
| 381 |
+
|
| 382 |
+
- In R: `survey::svydesign(ids = ~PPSU, strata = ~PSTRAT, weights = ~WTFA_A, nest = TRUE, data = adult)`.
|
| 383 |
+
- Use the weight of the file the variables come from (person, sample adult, sample child,
|
| 384 |
+
supplement); the imputed income files carry no weights, join them to the file whose weight you use
|
| 385 |
+
and combine the implicates with Rubin's rules.
|
| 386 |
+
- **Pooling years** (NCHS variance estimation guidance, see sources): divide each weight by the
|
| 387 |
+
number of years pooled.
|
| 388 |
+
- Years within one sample design period (1997–2005, 2006–2015, 2016–2018) are pooled as one
|
| 389 |
+
sample with that period's design variables; do not treat the years as independent.
|
| 390 |
+
- Across design periods (2005/2006, 2015/2016), treat the periods as independent and create a
|
| 391 |
+
stratum variable with distinct values per period (for example, add 1000 to the 2016+
|
| 392 |
+
`PSTRAT`), because the codes are not related across periods.
|
| 393 |
+
- 2019 and later: NCHS states that public-use files from 2019 on, including 2025 (first year of
|
| 394 |
+
the 2025 sample redesign), can be pooled with `PSTRAT`/`PPSU` as they are. For pooled 2019–2020
|
| 395 |
+
sample adult estimates use `WTSA_P` (`ADULTPART20`) for the 2020 records.
|
| 396 |
+
- The 2019 questionnaire, file structure and weighting changed: pooling 1997–2018 with 2019+ data
|
| 397 |
+
needs harmonised variables and care; NCHS gives no public-use recipe for it.
|
| 398 |
+
- The 2025 files are smaller: NCHS reports budget-driven sample reductions in the first year of the
|
| 399 |
+
2025 design and a data-collection pause from 1 October to 17 November 2025.
|
| 400 |
+
- Singleton PSUs: 2003, 2005 and 2007 sample child (and 2007 child CAM) files contain PSUs with a
|
| 401 |
+
single respondent. NCHS published dummy records (`Design/2003SAMCHILD` etc., weight 1) that can be
|
| 402 |
+
appended for software that cannot handle them; or use `options(survey.lonely.psu = "adjust")`.
|
| 403 |
+
|
| 404 |
+
## Sources and processing
|
| 405 |
+
|
| 406 |
+
| Part | Source | Processing |
|
| 407 |
+
|---|---|---|
|
| 408 |
+
| 1997–2018 data | [NCHS FTP `Datasets/NHIS/<year>`](https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/NHIS/) fixed-width ASCII | Read with the column positions of the NCHS SAS input program (`Program_Code/NHIS/<year>`); `$` variables as text, others as numbers |
|
| 409 |
+
| 2019–2025 data | NCHS CSV files (`*csv.zip`) | Variable order and types from the NCHS SAS program; the CSV is used because the ASCII copy rounds weights to its field width (e.g. `WTFA_A` 13177.008 vs 13177.01) |
|
| 410 |
+
| Imputed income 1997–2004 | `Datasets/NHIS/<year>_imputed_income` | No SAS program on the FTP: layout of the 2005 `INCMIMP.sas`, which is identical to the NCHS dataset documentation `datdocYY.pdf` (person number `PX` through 2003) |
|
| 411 |
+
| Pair weights | NCHS SAS data sets (`final_pair_weightYYYY.sas7bdat`) | `haven::read_sas` |
|
| 412 |
+
| 2016 revised weights | NCHS CSV (`2016/RWCSV`) | IDs as text, weights as numbers |
|
| 413 |
+
| Linked mortality | [NCHS public-use linked mortality files](https://www.cdc.gov/nchs/linked-data/mortality-files/index.html) | NHIS layout of the NCHS `SAS_ReadInProgramAllSurveys.sas` |
|
| 414 |
+
| Dictionaries | NCHS SAS programs + codebooks | See below |
|
| 415 |
+
|
| 416 |
+
Reading rules (exactly what the NCHS SAS programs do): blank numeric fields and `.` are missing;
|
| 417 |
+
implied decimals of the INPUT statement (`WTFA 22-29 .3`) are applied only when the field has no
|
| 418 |
+
decimal point; blank character fields are null; leading and trailing blanks of character fields
|
| 419 |
+
are removed. Nothing is recoded, top-coded, imputed or dropped. The SAS programs are parsed as text;
|
| 420 |
+
nothing downloaded is executed.
|
| 421 |
+
|
| 422 |
+
**Dictionaries.** `VARIABLES.parquet` (year, component, file, variable, position, start, end,
|
| 423 |
+
width, implied_decimals, type, label, sas_format, n_nonmissing, n_distinct, label_source,
|
| 424 |
+
question_id, question_text, universe, universe_description, sources, recodes, keywords, notes,
|
| 425 |
+
module, section, in_codebook, codebook) and `VALUES.parquet` (year, component, file, variable, code,
|
| 426 |
+
description, count_data, value_source, sas_format, count_published, value_order):
|
| 427 |
+
|
| 428 |
+
- labels, positions and value labels come from the NCHS SAS programs (`label_source`);
|
| 429 |
+
- question text, universe and notes come from the NCHS codebooks: the 1997–2003 codebooks
|
| 430 |
+
(`<file>.pdf`), the 2004–2018 layout documents (`<file>_layout.pdf`) and the 2019+ codebooks
|
| 431 |
+
(`<File>-codebook.pdf`), parsed from their text (`codebook` names the document);
|
| 432 |
+
- `count_published` is the unweighted frequency printed in the 1997–2003 and 2019+ codebooks;
|
| 433 |
+
`count_data` is the count in the Parquet file (ranges such as `01-25` are summed; open ranges
|
| 434 |
+
such as `LOW-HIGH` have none). `value_source = "codebook"` marks categories that appear only
|
| 435 |
+
in the codebook (for example `<Blank: Not in universe>`).
|
| 436 |
+
|
| 437 |
+
**Dictionary coverage.** 64,117 file × variable rows: 64,095 have a label, 53,473 are matched to a
|
| 438 |
+
codebook entry (45,543 with question text, 52,491 with a universe). 361,719 value rows, of which
|
| 439 |
+
123,643 carry a published frequency (1997–2003 and 2019–2025). Files without a codebook (labels
|
| 440 |
+
and value formats from the SAS program only): imputed income files, linked mortality, revised
|
| 441 |
+
weights, pair weights (labels of the SAS data set), birth weight `SC_BWT`, `RATCAT07`, `SAD_WGTS`
|
| 442 |
+
and the 2006 paradata. 2004–2018 layout documents carry no frequencies, so `count_published` is
|
| 443 |
+
empty for those years (`count_data` is always filled).
|
| 444 |
+
|
| 445 |
+
**Validation** (`pipeline/05_validate.R`; every check with its source is in `metadata/VALIDATION.parquet`):
|
| 446 |
+
|
| 447 |
+
- **825 checks, all passed.**
|
| 448 |
+
- Row counts: 223 files equal the record count printed by NCHS (1997–2003 codebook headers,
|
| 449 |
+
`RECTYPE` frequencies of the 2004–2018 frequency reports and 2019+ codebooks); the 2019–2024
|
| 450 |
+
Sample Adult / Sample Child files equal the interviewed counts of Table 2 of the 2024 Survey
|
| 451 |
+
Description (2020: `ADULTPART20` = 21,153; `ADULT20` also holds the 10,415 re-interviewed 2019
|
| 452 |
+
adults).
|
| 453 |
+
- Published frequencies: all 123,643 published unweighted frequencies equal the counts in the
|
| 454 |
+
Parquet files (87 files).
|
| 455 |
+
- Layout: every fixed-width record fits the SAS layout and no numeric field failed to parse
|
| 456 |
+
(406 files).
|
| 457 |
+
- Second NCHS copy: 71 files of 2015–2025 agree cell by cell with the other format NCHS
|
| 458 |
+
publishes (1997–2018 Parquet vs the CSV copy; 2019+ Parquet vs the ASCII copy, within the
|
| 459 |
+
ASCII rounding). Two NCHS differences are explained, not errors: the 2015–2018 CSV copies store
|
| 460 |
+
`BMI` without its implied decimals (2358 for 23.58), and the 2016 Sample Child CSV copy has the
|
| 461 |
+
original weights while the ASCII file (used here) has the revised 2016 weights (all 2016 ASCII
|
| 462 |
+
core files equal the `*_REVWTS` files). In 2021 `PARADATA21`, 11 character flags are `.` in the
|
| 463 |
+
ASCII copy and blank in the CSV.
|
| 464 |
+
- Linked mortality: every `PUBLICID` of the 22 files matches one person of the same year's
|
| 465 |
+
`PERSONSX`. 1997–2014 files cover all persons; 2015–2018 files cover sample adults and sample
|
| 466 |
+
children only, as NCHS released them.
|
| 467 |
+
- Published estimates, reproduced with `survey` (Taylor series, `PSU` nested in strata, lonely
|
| 468 |
+
PSU "adjust"): current cigarette smoking among adults, 2005 20.90% (published 20.9%,
|
| 469 |
+
MMWR 2006;55:1145), 2010 19.35% (19.3%, MMWR 2011;60:1207), 2018 13.73% (13.7%,
|
| 470 |
+
MMWR 2019;68:1013), 2019 13.98% (14.0%, MMWR 2020;69:1736).
|
| 471 |
+
|
| 472 |
+
**Coverage.** Every data file in the NCHS FTP folders `Datasets/NHIS/1997` … `2025` and the
|
| 473 |
+
`<year>_imputed_income` and `2006_paradata` folders, and the NHIS linked mortality files for
|
| 474 |
+
1997–2018. Not included: survey years 1963–1996 (different file structures), CSV copies of the
|
| 475 |
+
same files, the restricted-use files of the NCHS Research Data Center, and IPUMS NHIS (its terms
|
| 476 |
+
do not allow redistribution).
|
| 477 |
+
|
| 478 |
+
## Licence and citation
|
| 479 |
+
|
| 480 |
+
- **NHIS and linked mortality:** NCHS public-use data, U.S. Government works in the public domain
|
| 481 |
+
("…is in the public domain, and may be freely used or reproduced without obtaining copyright
|
| 482 |
+
permission", [CDC](https://www.cdc.gov/other/agencymaterials.html)). Cite: National Center for
|
| 483 |
+
Health Statistics. *National Health Interview Survey, <year>.* Public-use data file and
|
| 484 |
+
documentation. Hyattsville, MD: NCHS, Centers for Disease Control and Prevention.
|
| 485 |
+
- This compilation (pipeline, dictionaries, layout) is released under CC0-1.0.
|
| 486 |
+
|
| 487 |
+
Data users must follow the [NCHS data use agreement](https://www.cdc.gov/nchs/data_access/restrictions.htm):
|
| 488 |
+
use the data for statistical reporting and analysis only, make no attempt to learn the identity of
|
| 489 |
+
any person or household, and do not link the data with individually identifiable data from other
|
| 490 |
+
NCHS or non-NCHS datasets.
|
data/2013/Core/FAMILYXX.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d992a6d2c40eb248a4bd9eb1fb92ccee3728c1c0d1192857480418bcbdc976ff
|
| 3 |
+
size 1162967
|
data/2013/Core/HOUSEHLD.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eb00eb80f2c97528d1cd7f35094df710d4e0367eaa8e464603e2697e93247ea5
|
| 3 |
+
size 503273
|
data/2013/Core/PERSONSX.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5da0ef1c9491d7f82f3eab12f5cfe914eef59733955a03cb7a8d668196ba5c9b
|
| 3 |
+
size 5033135
|
data/2013/Core/SAMADULT.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:184c9c72c7ebb9451dfd3831ac9750eb3610c28a43a77412fa2524104cd8a0ac
|
| 3 |
+
size 4009019
|
data/2013/Core/SAMCHILD.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:362f1f1c2320ec832e24b4ccc7ecd11436ead6b120415e66288c62635c960a70
|
| 3 |
+
size 661114
|
data/2013/Dictionary/VALUES.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f78f4fd810df00b5199ba255ceb604da589f76cb06890ab27354e5e222424bbf
|
| 3 |
+
size 60190
|
data/2013/Dictionary/VARIABLES.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:96ca7c6dd22f7e5db03539cc4f8c00e27307a289692c722c2fe8d47c35b45b2d
|
| 3 |
+
size 160571
|
data/2013/ImputedIncome/INCMIMP1.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a583abd43359d6c11fb1beca2102066db542bab72f22b8fa83ef281068411ea0
|
| 3 |
+
size 694594
|
data/2013/ImputedIncome/INCMIMP2.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:86b2119e2b9a44e6f4efa57de9793f6a43edcb8d17cc8c07316502f298371b80
|
| 3 |
+
size 694136
|
data/2013/ImputedIncome/INCMIMP3.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7b2d65d72789207522a88aab7a81d546724757d2ac44c9767d3690af189183b0
|
| 3 |
+
size 694958
|
data/2013/ImputedIncome/INCMIMP4.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fb0a4652b61a8dd1b8d2295447426e69a9a1ca8ea8d8ac461582a56aa2ac7ca3
|
| 3 |
+
size 693566
|
data/2013/ImputedIncome/INCMIMP5.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:56456c824d67e05c30941e8d301ee5cebd4ca163702b63f2df5de68fb5196951
|
| 3 |
+
size 694449
|
data/2013/Injury/INJPOIEP.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6fc404415fbc78d7067e0ac1c13684f412cf1c37d30b1c189c501ec5396e92c0
|
| 3 |
+
size 96992
|
data/2013/Mortality/NHIS_2013_MORT_2019_PUBLIC.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6f409631e9fa07df9945a230a7ccee4c4da01c5bc94a74bd9124ab8d1bcda28a
|
| 3 |
+
size 638093
|
data/2013/Paradata/PARADATA.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e97a3acf8b6d0f80b29856091c1e5a038d062b89e9d2bfc1c1b98b6864e2547f
|
| 3 |
+
size 1336140
|
data/2013/Supplement/FMLYDISB.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6de3f5ff14ad6d6ac32db10be25eef4fdd0cdae7a97e289ea1b378c87e35cf6
|
| 3 |
+
size 351785
|
data/2013/Supplement/FUNCDISB.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a0596d7782594af7bd0118df3b114c39b24fff802f1189bd3fff171bc714f3b2
|
| 3 |
+
size 301889
|
data/2014/Core/FAMILYXX.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1993e361da6a43e433761b382c479a81fe53f7c6a958ae519e0ce770c5c23021
|
| 3 |
+
size 1211103
|
data/2014/Core/HOUSEHLD.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8915a42be0e581a2a70674bb9514580be7a49a90e0a82f66a755a09cc17939a4
|
| 3 |
+
size 554255
|
data/2014/Core/PERSONSX.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3454de60f39062ce7fe3446f7c29c5cbb39f95484231929a4e4ff47e7884a828
|
| 3 |
+
size 5544983
|
data/2014/Core/SAMADULT.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6bc9829891c4dca1ea9a018266a12a65d8624d68f5327ccee193996f4cc64e5c
|
| 3 |
+
size 4524691
|
data/2014/Dictionary/VALUES.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a743137fc78eec8e5f76eb27a58d68c1449abd25c82cf6a263680bcefaf81ed3
|
| 3 |
+
size 62111
|
data/2014/Dictionary/VARIABLES.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ee37801a90fc68b8bd9f9f1131cc0a95d2c672eeb61d5f80b6f66790733ca41f
|
| 3 |
+
size 165267
|
data/2014/ImputedIncome/INCMIMP1.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d58613c6484aeb7bcfd190b86d2510118012ad25429136fa05121f441c65be72
|
| 3 |
+
size 742546
|
data/2014/ImputedIncome/INCMIMP2.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5574c8fec34909e7c561d5c8c5033f5e1e707f39e5e689c7a8b2f943ca983b03
|
| 3 |
+
size 743098
|
data/2014/ImputedIncome/INCMIMP3.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e935498928abd0a15d9aea9a3cdfe5af92c47c756f901f74b5a9ae1bd6ff224e
|
| 3 |
+
size 741408
|
data/2014/ImputedIncome/INCMIMP4.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f2a6a94b403141f7aaf51d040d4355d3ba7a7b50f46eaabea13df5bcb8681024
|
| 3 |
+
size 743291
|
data/2014/ImputedIncome/INCMIMP5.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03e8a35acaa8d709b0d6fb34a3706aa300aaf8a9fc09c927a47fc44f4e895f5c
|
| 3 |
+
size 745097
|
data/2014/Injury/INJPOIEP.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:190e33e7c7c9e60a14df4bf55224ae9126063fd6de9adef0bfd55614f695b65d
|
| 3 |
+
size 99941
|
data/2014/Mortality/NHIS_2014_MORT_2019_PUBLIC.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:03a0180bf589ae18fba47d4064e7d55879793a06435f43e010fc0ed132dfc346
|
| 3 |
+
size 668769
|
data/2014/Paradata/PARADATA.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1700a5fff1dc49a8775e0b0881eb4f87acbe3ec59326993158a54506e4e3a40d
|
| 3 |
+
size 1597995
|
data/2014/Supplement/FMLYDISB.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:44de12234eb5d981cc64de8a8800de1b52c43255c70bb2591404cdf86efb5d6e
|
| 3 |
+
size 374125
|
data/2014/Supplement/FUNCDISB.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:111fa4747d0be54417b130f4972df68d30b30335f7453df5943d63e55e9075b5
|
| 3 |
+
size 315365
|
metadata/VALIDATION.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f11ae2af5effbce39cc078afc549c2f74892c45c5e0262da44582e3a055dc16e
|
| 3 |
+
size 12834
|
pipeline/00_config.R
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# 00_config.R: shared paths, year table and helpers for the NHIS pipeline
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Pipeline: NCHS NHIS public-use files (ftp.cdc.gov) -> raw mirror -> Parquet
|
| 5 |
+
# (Hugging Face dataset jamesjiadazhan/NHIS). Modelled on the NHANES pipeline
|
| 6 |
+
# (../../NHANES/pipeline). Run every step from this folder:
|
| 7 |
+
# Rscript 01_catalog.R; Rscript 02_download.R; Rscript 03_convert.R; ...
|
| 8 |
+
# Scope: survey years 1997-2025 (the 1997 redesign onward), the imputed income
|
| 9 |
+
# files, the 2006 paradata file and the NCHS public-use linked mortality files
|
| 10 |
+
# (NHIS 1997-2018, follow-up through 2019). Earlier years (1963-1996) use other
|
| 11 |
+
# file structures and are not included.
|
| 12 |
+
# =============================================================================
|
| 13 |
+
|
| 14 |
+
root <- normalizePath("..", mustWork = TRUE)
|
| 15 |
+
raw_dir <- file.path(root, "raw")
|
| 16 |
+
out_dir <- file.path(root, "parquet")
|
| 17 |
+
log_dir <- file.path(root, "logs")
|
| 18 |
+
tmp_root <- file.path(log_dir, "tmp") # unpacked ZIP members (deleted after use)
|
| 19 |
+
for (d in c(raw_dir, out_dir, log_dir, tmp_root)) dir.create(d, recursive = TRUE, showWarnings = FALSE)
|
| 20 |
+
|
| 21 |
+
ftp <- "https://ftp.cdc.gov"
|
| 22 |
+
nchs <- "/pub/Health_Statistics/NCHS"
|
| 23 |
+
years <- 1997:2025
|
| 24 |
+
|
| 25 |
+
# -----------------------------------------------------------------------------
|
| 26 |
+
# Survey eras: design variables and the NCHS sample design periods
|
| 27 |
+
# -----------------------------------------------------------------------------
|
| 28 |
+
# Sample design periods (NCHS variance estimation guidance): 1995-2005,
|
| 29 |
+
# 2006-2015, 2016-2018 and the 2019 questionnaire redesign (same 2016 sample
|
| 30 |
+
# design, new files and variable names).
|
| 31 |
+
design_period <- function(y) {
|
| 32 |
+
ifelse(y <= 2005, "1995-2005", ifelse(y <= 2015, "2006-2015",
|
| 33 |
+
ifelse(y <= 2018, "2016-2018", "2019+ (redesigned questionnaire)")
|
| 34 |
+
))
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
# -----------------------------------------------------------------------------
|
| 38 |
+
# FTP listing helpers
|
| 39 |
+
# -----------------------------------------------------------------------------
|
| 40 |
+
|
| 41 |
+
# Parse one IIS directory listing on ftp.cdc.gov into (href, size, date, dir).
|
| 42 |
+
list_ftp <- function(path) {
|
| 43 |
+
url <- paste0(ftp, path)
|
| 44 |
+
txt <- NULL
|
| 45 |
+
for (i in 1:4) {
|
| 46 |
+
txt <- tryCatch(paste(readLines(url, warn = FALSE), collapse = "\n"),
|
| 47 |
+
error = function(e) NULL
|
| 48 |
+
)
|
| 49 |
+
if (!is.null(txt)) break
|
| 50 |
+
Sys.sleep(2^i)
|
| 51 |
+
}
|
| 52 |
+
if (is.null(txt)) stop("cannot list ", url)
|
| 53 |
+
rx <- paste0(
|
| 54 |
+
"([0-9]{1,2}/[0-9]{1,2}/[0-9]{4}) +([0-9]{1,2}:[0-9]{2} [AP]M) +",
|
| 55 |
+
"(<dir>|[0-9]+) <A HREF=\"([^\"]+)\">"
|
| 56 |
+
)
|
| 57 |
+
m <- regmatches(txt, gregexpr(rx, txt))[[1]]
|
| 58 |
+
if (!length(m)) {
|
| 59 |
+
return(data.frame(href = character(), size = numeric(), date = character(), dir = logical()))
|
| 60 |
+
}
|
| 61 |
+
p <- regmatches(m, regexec(rx, m))
|
| 62 |
+
data.frame(
|
| 63 |
+
href = vapply(p, `[`, "", 5),
|
| 64 |
+
size = suppressWarnings(as.numeric(vapply(p, `[`, "", 4))),
|
| 65 |
+
date = vapply(p, `[`, "", 2),
|
| 66 |
+
dir = vapply(p, `[`, "", 4) == "<dir>",
|
| 67 |
+
stringsAsFactors = FALSE
|
| 68 |
+
)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
# Local mirror path for an ftp.cdc.gov URL (keeps the NCHS folder layout).
|
| 72 |
+
raw_path <- function(url) {
|
| 73 |
+
p <- sub("^https?://[^/]+/pub/Health_Statistics/NCHS/", "", url)
|
| 74 |
+
file.path(raw_dir, p)
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
# Append a line to a log file.
|
| 78 |
+
log_line <- function(file, ...) {
|
| 79 |
+
cat(format(Sys.time(), "%F %T"), " ", ..., "\n",
|
| 80 |
+
sep = "", file = file.path(log_dir, file),
|
| 81 |
+
append = TRUE
|
| 82 |
+
)
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
# Polite parallel download of missing files: at most 4 connections to the
|
| 86 |
+
# host, resumable, three attempts with backoff; failures logged and removed.
|
| 87 |
+
download_missing <- function(urls, dest, log = "download.log") {
|
| 88 |
+
for (attempt in 1:3) {
|
| 89 |
+
need <- !file.exists(dest) | file.size(dest) == 0
|
| 90 |
+
if (!any(need)) {
|
| 91 |
+
return(invisible(TRUE))
|
| 92 |
+
}
|
| 93 |
+
u <- urls[need]
|
| 94 |
+
d <- dest[need]
|
| 95 |
+
for (dd in unique(dirname(d))) dir.create(dd, recursive = TRUE, showWarnings = FALSE)
|
| 96 |
+
# multi_download() has no connection limit argument: run batches of
|
| 97 |
+
# four transfers so at most four connections are open at once.
|
| 98 |
+
res <- do.call(rbind, lapply(split(seq_along(u), ceiling(seq_along(u) / 4)), function(k) {
|
| 99 |
+
curl::multi_download(u[k], d[k],
|
| 100 |
+
resume = TRUE, progress = FALSE, multi_timeout = Inf,
|
| 101 |
+
multiplex = FALSE, useragent = "Mozilla/5.0 (research data pipeline)"
|
| 102 |
+
)
|
| 103 |
+
}))
|
| 104 |
+
bad <- !res$success | is.na(res$status_code) | res$status_code >= 400
|
| 105 |
+
for (i in which(bad)) {
|
| 106 |
+
log_line(log, "FAILED(", attempt, ") ", res$url[i], " status=", res$status_code[i], " ", res$error[i])
|
| 107 |
+
unlink(res$destfile[i])
|
| 108 |
+
}
|
| 109 |
+
log_line(log, "attempt ", attempt, ": downloaded ", sum(!bad), " failed ", sum(bad))
|
| 110 |
+
if (!any(bad)) break
|
| 111 |
+
Sys.sleep(10 * attempt)
|
| 112 |
+
}
|
| 113 |
+
invisible(TRUE)
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
# Read the catalog written by 01_catalog.R (one row per downloadable file).
|
| 117 |
+
read_catalog <- function() {
|
| 118 |
+
x <- utils::read.csv(file.path(root, "catalog_ftp_listing.csv"), stringsAsFactors = FALSE)
|
| 119 |
+
x$raw <- raw_path(x$url)
|
| 120 |
+
x
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
# Write a data frame as zstd Parquet without R metadata (atomic rename).
|
| 124 |
+
write_parquet_clean <- function(d, path, level = 9) {
|
| 125 |
+
d <- as.data.frame(d, stringsAsFactors = FALSE)
|
| 126 |
+
tab <- arrow::arrow_table(d)
|
| 127 |
+
tab$metadata$r <- NULL
|
| 128 |
+
dir.create(dirname(path), recursive = TRUE, showWarnings = FALSE)
|
| 129 |
+
tmp <- paste0(path, ".tmp")
|
| 130 |
+
arrow::write_parquet(tab, tmp, compression = "zstd", compression_level = level)
|
| 131 |
+
file.rename(tmp, path)
|
| 132 |
+
}
|
pipeline/01_catalog.R
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# 01_catalog.R: crawl ftp.cdc.gov and list every NHIS file in scope
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Lists, for survey years 1997-2025:
|
| 5 |
+
# Datasets/NHIS/<year>/ data archives (ZIP of ASCII / CSV)
|
| 6 |
+
# Datasets/NHIS/<year>_imputed_income/ imputed income archives + programs
|
| 7 |
+
# Datasets/NHIS/2006_paradata/ 2006 paradata
|
| 8 |
+
# Program_Code/NHIS/<year>/ SAS / SPSS / Stata input programs
|
| 9 |
+
# Dataset_Documentation/NHIS/<year>/ codebooks, summaries, survey description
|
| 10 |
+
# datalinkage/linked_mortality/ NHIS_<year>_MORT_2019_PUBLIC.dat + read-in
|
| 11 |
+
# Writes ../catalog_ftp_listing.csv: year, kind, folder, file, url, size, date.
|
| 12 |
+
# Re-running re-crawls (cheap: about 90 directory listings, one at a time).
|
| 13 |
+
# =============================================================================
|
| 14 |
+
source("00_config.R")
|
| 15 |
+
out <- file.path(root, "catalog_ftp_listing.csv")
|
| 16 |
+
|
| 17 |
+
# Recursively list a folder (depth-limited) and tag rows with year and kind.
|
| 18 |
+
crawl <- function(path, year, kind, depth = 2) {
|
| 19 |
+
x <- tryCatch(list_ftp(path), error = function(e) {
|
| 20 |
+
log_line("catalog.log", "cannot list ", path)
|
| 21 |
+
NULL
|
| 22 |
+
})
|
| 23 |
+
if (is.null(x) || !nrow(x)) {
|
| 24 |
+
return(NULL)
|
| 25 |
+
}
|
| 26 |
+
files <- x[!x$dir, ]
|
| 27 |
+
files <- files[!grepl("/\\.cache\\+?$", files$href), ]
|
| 28 |
+
res <- if (nrow(files)) {
|
| 29 |
+
data.frame(
|
| 30 |
+
year = year, kind = kind, folder = path,
|
| 31 |
+
file = basename(files$href), url = paste0(ftp, files$href),
|
| 32 |
+
size = files$size, date = files$date, stringsAsFactors = FALSE
|
| 33 |
+
)
|
| 34 |
+
}
|
| 35 |
+
if (depth > 0) {
|
| 36 |
+
for (h in x$href[x$dir]) res <- rbind(res, crawl(h, year, kind, depth - 1))
|
| 37 |
+
}
|
| 38 |
+
res
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
top <- list_ftp(paste0(nchs, "/Datasets/NHIS/"))
|
| 42 |
+
top$name <- basename(sub("/$", "", top$href))
|
| 43 |
+
rows <- list()
|
| 44 |
+
for (y in years) {
|
| 45 |
+
rows[[length(rows) + 1]] <- crawl(sprintf("%s/Datasets/NHIS/%d/", nchs, y), y, "data")
|
| 46 |
+
inc <- top$href[top$dir & tolower(top$name) == paste0(y, "_imputed_income")]
|
| 47 |
+
for (h in inc) rows[[length(rows) + 1]] <- crawl(h, y, "imputed_income")
|
| 48 |
+
para <- top$href[top$dir & tolower(top$name) == paste0(y, "_paradata")]
|
| 49 |
+
for (h in para) rows[[length(rows) + 1]] <- crawl(h, y, "paradata")
|
| 50 |
+
rows[[length(rows) + 1]] <- crawl(sprintf("%s/Program_Code/NHIS/%d/", nchs, y), y, "program")
|
| 51 |
+
rows[[length(rows) + 1]] <- crawl(
|
| 52 |
+
sprintf("%s/Dataset_Documentation/NHIS/%d/", nchs, y), y, "documentation"
|
| 53 |
+
)
|
| 54 |
+
cat(y, "")
|
| 55 |
+
}
|
| 56 |
+
mort <- crawl(paste0(nchs, "/datalinkage/linked_mortality/"), NA, "mortality", depth = 0)
|
| 57 |
+
mort$year <- suppressWarnings(as.integer(sub("^NHIS_([0-9]{4})_MORT.*", "\\1", mort$file)))
|
| 58 |
+
keep <- (!is.na(mort$year) & mort$year %in% years & grepl("^NHIS_", mort$file)) |
|
| 59 |
+
grepl("ReadInProgram", mort$file)
|
| 60 |
+
mort <- mort[keep, ]
|
| 61 |
+
cat_x <- do.call(rbind, c(rows, list(mort)))
|
| 62 |
+
utils::write.csv(cat_x, out, row.names = FALSE)
|
| 63 |
+
cat("\nfiles:", nrow(cat_x), " GB:", round(sum(cat_x$size, na.rm = TRUE) / 2^30, 2), "\n")
|
| 64 |
+
print(tapply(cat_x$size, cat_x$kind, function(s) round(sum(s, na.rm = TRUE) / 2^20)))
|
pipeline/02_download.R
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# 02_download.R: mirror every catalogued NHIS file into ../raw
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Downloads the data archives, imputed income files, input programs, codebooks
|
| 5 |
+
# and linked mortality files listed in ../catalog_ftp_listing.csv into
|
| 6 |
+
# ../raw/<NCHS folder layout>. At most 4 connections; failures retried with
|
| 7 |
+
# backoff and logged to ../logs/download.log. Re-running fetches only files
|
| 8 |
+
# that are missing or whose size differs from the FTP listing.
|
| 9 |
+
# =============================================================================
|
| 10 |
+
source("00_config.R")
|
| 11 |
+
x <- read_catalog()
|
| 12 |
+
# Re-fetch files whose size no longer matches the listing (updated on FTP).
|
| 13 |
+
stale <- file.exists(x$raw) & !is.na(x$size) & file.size(x$raw) != x$size
|
| 14 |
+
if (any(stale)) {
|
| 15 |
+
log_line("download.log", "size changed, re-fetching: ", paste(x$url[stale], collapse = " "))
|
| 16 |
+
unlink(x$raw[stale])
|
| 17 |
+
}
|
| 18 |
+
ord <- order(x$size)
|
| 19 |
+
for (chunk in split(ord, ceiling(seq_along(ord) / 100))) {
|
| 20 |
+
download_missing(x$url[chunk], x$raw[chunk])
|
| 21 |
+
cat(sum(file.exists(x$raw)), "/", nrow(x), "\n")
|
| 22 |
+
}
|
| 23 |
+
bad <- !file.exists(x$raw) | (!is.na(x$size) & file.size(x$raw) != x$size)
|
| 24 |
+
writeLines(x$url[bad], file.path(log_dir, "download_missing.txt"))
|
| 25 |
+
cat("Missing or size mismatch:", sum(bad), "\n")
|
pipeline/03_convert.R
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# 03_convert.R: NHIS ASCII / SAS / CSV public-use files -> Parquet
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# One Parquet file per original NCHS data file, under
|
| 5 |
+
# ../parquet/data/<year>/<component>/<FILE>.parquet
|
| 6 |
+
# (inventory and naming: files_spec.R). Fixed-width ASCII files are read with
|
| 7 |
+
# the column positions of the NCHS SAS input program (sas_setup.R):
|
| 8 |
+
# * "$" variables stay character (leading/trailing blanks trimmed; a blank
|
| 9 |
+
# field becomes null, which is how SAS reads a blank character field);
|
| 10 |
+
# * other variables are numeric (double); a blank or "." field is null; an
|
| 11 |
+
# implied decimal in the INPUT statement (e.g. "WTFA 22-29 .3") is applied
|
| 12 |
+
# exactly as SAS does: only when the field has no explicit decimal point.
|
| 13 |
+
# No value is recoded, imputed or dropped. ZIP members are extracted to a
|
| 14 |
+
# temporary folder and deleted after conversion (the ZIP stays in raw/).
|
| 15 |
+
# Writes ../logs/meta/<year>__<FILE>.rds (manifest row, per-column summary,
|
| 16 |
+
# value counts) for the dictionary, manifest and validation steps.
|
| 17 |
+
# Usage: Rscript 03_convert.R [workers] (default 2)
|
| 18 |
+
# =============================================================================
|
| 19 |
+
source("00_config.R")
|
| 20 |
+
source("sas_setup.R")
|
| 21 |
+
source("files_spec.R")
|
| 22 |
+
source("readers.R")
|
| 23 |
+
args <- commandArgs(TRUE)
|
| 24 |
+
workers <- if (length(args) && grepl("^[0-9]+$", args[1])) as.integer(args[1]) else 2L
|
| 25 |
+
meta_dir <- file.path(log_dir, "meta")
|
| 26 |
+
dir.create(meta_dir, showWarnings = FALSE)
|
| 27 |
+
|
| 28 |
+
# Per-column summary and value counts (columns with at most 500 distinct
|
| 29 |
+
# values) kept for the dictionary.
|
| 30 |
+
summarise_cols <- function(d, lay) {
|
| 31 |
+
cols <- data.frame(
|
| 32 |
+
variable = names(d), position = seq_along(d),
|
| 33 |
+
type = vapply(d, function(v) if (is.character(v)) "string" else "double", ""),
|
| 34 |
+
n_nonmissing = vapply(d, function(v) sum(!is.na(v)), 1),
|
| 35 |
+
n_distinct = vapply(d, function(v) length(unique(v[!is.na(v)])), 1),
|
| 36 |
+
stringsAsFactors = FALSE
|
| 37 |
+
)
|
| 38 |
+
cols <- cbind(cols, lay[match(cols$variable, lay$variable), c("start", "end", "width", "decimals", "label", "format")])
|
| 39 |
+
counts <- lapply(names(d)[cols$n_distinct <= 500], function(v) {
|
| 40 |
+
t <- table(d[[v]], useNA = "ifany")
|
| 41 |
+
data.frame(
|
| 42 |
+
variable = v, value = names(t), count = as.numeric(t),
|
| 43 |
+
stringsAsFactors = FALSE
|
| 44 |
+
)
|
| 45 |
+
})
|
| 46 |
+
list(columns = cols, counts = do.call(rbind, counts))
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Convert one inventory row; returns its manifest row (or an error row).
|
| 50 |
+
convert_row <- function(r) {
|
| 51 |
+
out <- file.path(out_dir, r$path)
|
| 52 |
+
meta <- file.path(meta_dir, paste0(r$year, "__", r$file, ".rds"))
|
| 53 |
+
if (file.exists(out) && file.exists(meta)) {
|
| 54 |
+
return(readRDS(meta)$manifest)
|
| 55 |
+
}
|
| 56 |
+
m <- NULL
|
| 57 |
+
res <- tryCatch(
|
| 58 |
+
{
|
| 59 |
+
m <- materialise(r)
|
| 60 |
+
src <- m$path
|
| 61 |
+
check <- list(reclen = c(NA, NA), bad = integer(0))
|
| 62 |
+
formats <- NULL
|
| 63 |
+
if (r$reader == "fwf") {
|
| 64 |
+
p <- program_layout(r$program, r$section)
|
| 65 |
+
lay <- p$layout
|
| 66 |
+
formats <- p$formats
|
| 67 |
+
rd <- read_fixed(src, lay)
|
| 68 |
+
d <- rd$data
|
| 69 |
+
check <- rd
|
| 70 |
+
} else if (r$reader == "csv") {
|
| 71 |
+
p <- program_layout(r$program, r$section)
|
| 72 |
+
lay <- p$layout
|
| 73 |
+
formats <- p$formats
|
| 74 |
+
rd <- read_csv_layout(src, lay)
|
| 75 |
+
d <- rd$data
|
| 76 |
+
check <- rd
|
| 77 |
+
if (length(rd$extra)) log_line("convert.log", r$year, " ", r$file, " CSV-only columns: ", paste(rd$extra, collapse = " "))
|
| 78 |
+
} else if (r$reader == "sas7bdat") {
|
| 79 |
+
d <- haven::read_sas(src)
|
| 80 |
+
lab <- vapply(d, function(v) {
|
| 81 |
+
l <- attr(v, "label", exact = TRUE)
|
| 82 |
+
if (is.null(l)) NA_character_ else as.character(l)
|
| 83 |
+
}, "")
|
| 84 |
+
d <- haven::zap_label(haven::zap_formats(haven::zap_widths(haven::zap_labels(d))))
|
| 85 |
+
d <- as.data.frame(d, stringsAsFactors = FALSE)
|
| 86 |
+
lay <- data.frame(
|
| 87 |
+
variable = names(d), position = seq_along(d), start = NA_integer_,
|
| 88 |
+
end = NA_integer_, width = NA_integer_, decimals = 0L,
|
| 89 |
+
type = vapply(d, function(v) if (is.character(v)) "string" else "double", ""),
|
| 90 |
+
label = unname(lab), format = NA_character_, stringsAsFactors = FALSE
|
| 91 |
+
)
|
| 92 |
+
} else if (r$reader == "revwts_csv") {
|
| 93 |
+
rv <- read_revwts(src)
|
| 94 |
+
d <- rv$data
|
| 95 |
+
lay <- rv$layout
|
| 96 |
+
} else {
|
| 97 |
+
stop("unknown reader ", r$reader)
|
| 98 |
+
}
|
| 99 |
+
sm <- summarise_cols(d, lay)
|
| 100 |
+
write_parquet_clean(d, out)
|
| 101 |
+
manifest <- data.frame(
|
| 102 |
+
year = r$year, component = r$component, file = r$file, stem = r$stem,
|
| 103 |
+
rows = nrow(d), columns = ncol(d), path = r$path,
|
| 104 |
+
parquet_bytes = file.size(out), source_url = r$source_url,
|
| 105 |
+
member = ifelse(is.na(r$member), "", r$member),
|
| 106 |
+
program = ifelse(is.na(r$program), "", sub(paste0(raw_dir, "/"), "", r$program)),
|
| 107 |
+
layout_note = r$layout_note,
|
| 108 |
+
source_md5 = unname(tools::md5sum(src)),
|
| 109 |
+
record_length_min = check$reclen[1], record_length_max = check$reclen[2],
|
| 110 |
+
layout_end = if (r$reader == "fwf") max(lay$end) else NA_integer_,
|
| 111 |
+
unparsed_numeric = sum(check$bad),
|
| 112 |
+
unparsed_vars = paste(names(check$bad), collapse = " "),
|
| 113 |
+
status = "ok", stringsAsFactors = FALSE
|
| 114 |
+
)
|
| 115 |
+
saveRDS(list(manifest = manifest, columns = sm$columns, counts = sm$counts, formats = formats), meta)
|
| 116 |
+
manifest
|
| 117 |
+
},
|
| 118 |
+
error = function(e) {
|
| 119 |
+
data.frame(
|
| 120 |
+
year = r$year, component = r$component, file = r$file, stem = r$stem,
|
| 121 |
+
rows = NA_integer_, columns = NA_integer_, path = r$path, parquet_bytes = NA_real_,
|
| 122 |
+
source_url = r$source_url, member = ifelse(is.na(r$member), "", r$member),
|
| 123 |
+
program = ifelse(is.na(r$program), "", r$program), layout_note = r$layout_note,
|
| 124 |
+
source_md5 = NA_character_, record_length_min = NA_integer_,
|
| 125 |
+
record_length_max = NA_integer_, layout_end = NA_integer_,
|
| 126 |
+
unparsed_numeric = NA_integer_, unparsed_vars = "",
|
| 127 |
+
status = paste("error:", conditionMessage(e)), stringsAsFactors = FALSE
|
| 128 |
+
)
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
if (!is.null(m) && length(m$cleanup)) unlink(m$cleanup, recursive = TRUE)
|
| 132 |
+
if (res$status != "ok") log_line("convert.log", r$year, " ", r$file, " ", res$status)
|
| 133 |
+
res
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
spec <- build_spec()
|
| 137 |
+
saveRDS(spec, file.path(log_dir, "files_spec.rds"))
|
| 138 |
+
only <- Sys.getenv("NHIS_ONLY") # optional regex on "<year>/<file>" for testing
|
| 139 |
+
if (nzchar(only)) spec <- spec[grepl(only, paste0(spec$year, "/", spec$file)), ]
|
| 140 |
+
rows <- split(spec, seq_len(nrow(spec)))
|
| 141 |
+
# Largest archives first so the two workers stay balanced.
|
| 142 |
+
rows <- rows[order(-file.size(spec$archive))]
|
| 143 |
+
res <- parallel::mclapply(rows, convert_row, mc.cores = workers, mc.preschedule = FALSE)
|
| 144 |
+
res <- do.call(rbind, res)
|
| 145 |
+
res <- res[order(res$year, res$component, res$file), ]
|
| 146 |
+
utils::write.csv(res, file.path(log_dir, "convert_status.csv"), row.names = FALSE)
|
| 147 |
+
cat("ok:", sum(res$status == "ok"), " errors:", sum(res$status != "ok"), "\n")
|
| 148 |
+
print(utils::head(res[res$status != "ok", c("year", "file", "status")], 30))
|
| 149 |
+
chk <- res[res$status == "ok" & (res$unparsed_numeric > 0 |
|
| 150 |
+
(!is.na(res$layout_end) & res$record_length_max != res$layout_end)), ]
|
| 151 |
+
cat("files with layout warnings:", nrow(chk), "\n")
|
| 152 |
+
print(utils::head(chk[c("year", "file", "record_length_min", "record_length_max", "layout_end", "unparsed_numeric", "unparsed_vars")], 40))
|
pipeline/04_dictionary.R
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# 04_dictionary.R: one variable dictionary per NHIS survey year
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# For every converted file of a year, combines
|
| 5 |
+
# * the NCHS SAS input program: column position, width, implied decimals,
|
| 6 |
+
# type, SAS label, format name and the PROC FORMAT value labels;
|
| 7 |
+
# * the NCHS codebook PDF of the file (codebook_pdf.R): question ID, question
|
| 8 |
+
# text, universe and universe description, sources, recodes, keywords,
|
| 9 |
+
# notes (and module/section for 2019+) and the published unweighted
|
| 10 |
+
# frequencies (1997-2003 and 2019+ codebooks);
|
| 11 |
+
# * the data themselves: non-missing and distinct counts per variable and
|
| 12 |
+
# the observed count of every coded value (count_data).
|
| 13 |
+
# Writes ../parquet/data/<year>/Dictionary/VARIABLES.parquet (one row per
|
| 14 |
+
# file x variable) and VALUES.parquet (one row per file x variable x code),
|
| 15 |
+
# and ../logs/dictionary_status.csv (sources and coverage per file).
|
| 16 |
+
# Parsed PDFs are cached in ../logs/codebook_cache/.
|
| 17 |
+
# =============================================================================
|
| 18 |
+
source("00_config.R")
|
| 19 |
+
source("sas_setup.R")
|
| 20 |
+
source("files_spec.R")
|
| 21 |
+
source("codebook_pdf.R")
|
| 22 |
+
meta_dir <- file.path(log_dir, "meta")
|
| 23 |
+
cache_dir <- file.path(log_dir, "codebook_cache")
|
| 24 |
+
dir.create(cache_dir, showWarnings = FALSE)
|
| 25 |
+
|
| 26 |
+
# Parse (or read from cache) the codebook of one inventory row.
|
| 27 |
+
codebook_for <- function(doc, year) {
|
| 28 |
+
if (is.na(doc) || !file.exists(doc)) {
|
| 29 |
+
return(NULL)
|
| 30 |
+
}
|
| 31 |
+
key <- file.path(cache_dir, paste0(year, "__", basename(doc), ".rds"))
|
| 32 |
+
if (file.exists(key)) {
|
| 33 |
+
return(readRDS(key))
|
| 34 |
+
}
|
| 35 |
+
style <- if (year >= 2019) "modern" else if (year <= 2003) "old" else "layout"
|
| 36 |
+
cb <- tryCatch(
|
| 37 |
+
switch(style,
|
| 38 |
+
modern = parse_modern(doc),
|
| 39 |
+
old = parse_old(doc),
|
| 40 |
+
layout = parse_layout(doc)
|
| 41 |
+
),
|
| 42 |
+
error = function(e) NULL
|
| 43 |
+
)
|
| 44 |
+
if (!is.null(cb)) {
|
| 45 |
+
cb$style <- style
|
| 46 |
+
cb$variables <- cb$variables[!duplicated(cb$variables$variable), ]
|
| 47 |
+
gen <- cb$variables$question_text %in% c("Generated variable", "Recode", "Generated")
|
| 48 |
+
cb$variables$question_text[gen] <- NA
|
| 49 |
+
saveRDS(cb, key)
|
| 50 |
+
}
|
| 51 |
+
cb
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
# Normalise a code for matching: numbers lose leading zeros.
|
| 55 |
+
norm_code <- function(x) {
|
| 56 |
+
x <- trimws(x)
|
| 57 |
+
n <- suppressWarnings(as.numeric(x))
|
| 58 |
+
ifelse(!is.na(n) & grepl("^[-+]?[0-9.]+$", x), format(n, scientific = FALSE, trim = TRUE, drop0trailing = TRUE), x)
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
# Observed count of a SAS format range in the data counts of one variable.
|
| 62 |
+
count_range <- function(code_raw, counts, is_char) {
|
| 63 |
+
if (is.null(counts) || !nrow(counts)) {
|
| 64 |
+
return(NA_real_)
|
| 65 |
+
}
|
| 66 |
+
obs <- counts[!is.na(counts$value), ]
|
| 67 |
+
cr <- trimws(code_raw)
|
| 68 |
+
if (toupper(cr) == "OTHER" || grepl("LOW|HIGH|<", cr, ignore.case = TRUE)) {
|
| 69 |
+
return(NA_real_)
|
| 70 |
+
}
|
| 71 |
+
if (cr %in% c(".", "' '", "\" \"")) {
|
| 72 |
+
return(sum(counts$count[is.na(counts$value)]))
|
| 73 |
+
}
|
| 74 |
+
parts <- trimws(strsplit(cr, ",")[[1]])
|
| 75 |
+
total <- 0
|
| 76 |
+
for (p in parts) {
|
| 77 |
+
p <- gsub("^['\"]|['\"]$", "", p)
|
| 78 |
+
if (grepl("^-?[0-9.]+\\s*-\\s*-?[0-9.]+$", p)) {
|
| 79 |
+
ab <- as.numeric(trimws(strsplit(sub("^(-?[0-9.]+)\\s*-\\s*(-?[0-9.]+)$", "\\1|\\2", p), "|", fixed = TRUE)[[1]]))
|
| 80 |
+
v <- suppressWarnings(as.numeric(obs$value))
|
| 81 |
+
total <- total + sum(obs$count[!is.na(v) & v >= ab[1] & v <= ab[2]])
|
| 82 |
+
} else if (!is_char && !is.na(suppressWarnings(as.numeric(p)))) {
|
| 83 |
+
v <- suppressWarnings(as.numeric(obs$value))
|
| 84 |
+
total <- total + sum(obs$count[!is.na(v) & v == as.numeric(p)])
|
| 85 |
+
} else if (is_char) {
|
| 86 |
+
total <- total + sum(obs$count[trimws(obs$value) == p])
|
| 87 |
+
} else {
|
| 88 |
+
return(NA_real_)
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
total
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
# Dictionary tables for one file (meta RDS + inventory row).
|
| 95 |
+
file_dictionary <- function(mt, r) {
|
| 96 |
+
mf <- mt$manifest
|
| 97 |
+
cols <- mt$columns
|
| 98 |
+
cb <- codebook_for(r$doc, r$year)
|
| 99 |
+
# Singleton-PSU dummy files share the layout of the full file: keep the
|
| 100 |
+
# codebook text but not the published frequencies of the full file.
|
| 101 |
+
if (isTRUE(r$singleton) && !is.null(cb)) cb$values <- cb$values[0, ]
|
| 102 |
+
v <- data.frame(
|
| 103 |
+
year = mf$year, component = mf$component, file = mf$file, variable = cols$variable,
|
| 104 |
+
position = cols$position, start = cols$start, end = cols$end, width = cols$width,
|
| 105 |
+
implied_decimals = cols$decimals, type = cols$type, label = cols$label,
|
| 106 |
+
sas_format = cols$format, n_nonmissing = cols$n_nonmissing, n_distinct = cols$n_distinct,
|
| 107 |
+
stringsAsFactors = FALSE
|
| 108 |
+
)
|
| 109 |
+
v$label_source <- switch(r$reader,
|
| 110 |
+
sas7bdat = "NCHS SAS data set labels",
|
| 111 |
+
revwts_csv = "NCHS revised-weights SAS import program",
|
| 112 |
+
paste0("NCHS SAS program ", basename(r$program))
|
| 113 |
+
)
|
| 114 |
+
fields <- c(
|
| 115 |
+
"question_id", "question_text", "universe", "universe_description", "sources",
|
| 116 |
+
"recodes", "keywords", "notes", "module", "section"
|
| 117 |
+
)
|
| 118 |
+
if (!is.null(cb) && nrow(cb$variables)) {
|
| 119 |
+
k <- match(v$variable, cb$variables$variable)
|
| 120 |
+
for (f in fields) v[[f]] <- cb$variables[[f]][k]
|
| 121 |
+
v$in_codebook <- !is.na(k)
|
| 122 |
+
miss_lab <- is.na(v$label) | !nzchar(v$label)
|
| 123 |
+
v$label[miss_lab] <- cb$variables$doc_label[k][miss_lab]
|
| 124 |
+
v$codebook <- ifelse(v$in_codebook, basename(r$doc), NA_character_)
|
| 125 |
+
} else {
|
| 126 |
+
for (f in fields) v[[f]] <- NA_character_
|
| 127 |
+
v$in_codebook <- FALSE
|
| 128 |
+
v$codebook <- NA_character_
|
| 129 |
+
}
|
| 130 |
+
if (r$stem == "MORT") {
|
| 131 |
+
v$universe <- NA_character_
|
| 132 |
+
v$notes <- "NCHS public-use linked mortality file; see the NCHS linked mortality documentation"
|
| 133 |
+
}
|
| 134 |
+
# Values: SAS format labels, matched to data counts and published counts.
|
| 135 |
+
vals <- NULL
|
| 136 |
+
fm <- mt$formats
|
| 137 |
+
if (!is.null(fm) && nrow(fm)) {
|
| 138 |
+
vf <- v[!is.na(v$sas_format), c("variable", "sas_format", "type")]
|
| 139 |
+
fm$fmt_order <- seq_len(nrow(fm))
|
| 140 |
+
vals <- merge(vf, fm, by.x = "sas_format", by.y = "format", sort = FALSE)
|
| 141 |
+
vals <- vals[order(match(vals$variable, v$variable), vals$fmt_order), ]
|
| 142 |
+
if (nrow(vals)) {
|
| 143 |
+
vals$count_data <- mapply(function(var, cr, ty) {
|
| 144 |
+
count_range(cr, mt$counts[mt$counts$variable == var, ], ty == "string")
|
| 145 |
+
}, vals$variable, vals$code_raw, vals$type)
|
| 146 |
+
vals$value_source <- "SAS format"
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
if (!is.null(vals) && nrow(vals)) {
|
| 150 |
+
vals <- vals[c("variable", "code", "label", "count_data", "value_source", "sas_format")]
|
| 151 |
+
names(vals)[3] <- "description"
|
| 152 |
+
vals$count_published <- NA_real_
|
| 153 |
+
}
|
| 154 |
+
if (!is.null(cb) && nrow(cb$values)) {
|
| 155 |
+
pv <- cb$values[cb$values$variable %in% v$variable, ]
|
| 156 |
+
if (!is.null(vals) && nrow(vals) && nrow(pv)) {
|
| 157 |
+
key_a <- paste(vals$variable, norm_code(vals$code))
|
| 158 |
+
key_b <- paste(pv$variable, norm_code(pv$code))
|
| 159 |
+
vals$count_published <- pv$count_published[match(key_a, key_b)]
|
| 160 |
+
pv <- pv[!key_b %in% key_a, ]
|
| 161 |
+
}
|
| 162 |
+
if (nrow(pv)) {
|
| 163 |
+
extra <- data.frame(
|
| 164 |
+
variable = pv$variable, code = pv$code, description = pv$description,
|
| 165 |
+
count_data = NA_real_, value_source = "codebook", sas_format = NA_character_,
|
| 166 |
+
count_published = pv$count_published, stringsAsFactors = FALSE
|
| 167 |
+
)
|
| 168 |
+
vals <- if (is.null(vals) || !nrow(vals)) extra else rbind(vals, extra)
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
if (!is.null(vals) && nrow(vals)) {
|
| 172 |
+
vals <- data.frame(year = mf$year, component = mf$component, file = mf$file, vals, stringsAsFactors = FALSE)
|
| 173 |
+
vals <- vals[order(match(vals$variable, v$variable), seq_len(nrow(vals))), ]
|
| 174 |
+
vals$value_order <- stats::ave(seq_len(nrow(vals)), vals$variable, FUN = seq_along)
|
| 175 |
+
}
|
| 176 |
+
status <- data.frame(
|
| 177 |
+
year = mf$year, file = mf$file, label_source = v$label_source[1],
|
| 178 |
+
codebook = ifelse(is.null(cb), NA_character_, basename(r$doc)),
|
| 179 |
+
codebook_style = ifelse(is.null(cb), NA_character_, cb$style),
|
| 180 |
+
codebook_records = ifelse(is.null(cb), NA_real_, cb$records),
|
| 181 |
+
variables = nrow(v), with_label = sum(!is.na(v$label) & nzchar(v$label)),
|
| 182 |
+
in_codebook = sum(v$in_codebook), with_question_text = sum(!is.na(v$question_text)),
|
| 183 |
+
with_universe = sum(!is.na(v$universe)), value_rows = NROW(vals),
|
| 184 |
+
values_with_published_count = if (is.null(vals)) 0 else sum(!is.na(vals$count_published)),
|
| 185 |
+
published_count_mismatch = if (is.null(vals)) 0 else sum(!is.na(vals$count_published) & !is.na(vals$count_data) & vals$count_published != vals$count_data),
|
| 186 |
+
stringsAsFactors = FALSE
|
| 187 |
+
)
|
| 188 |
+
list(variables = v, values = vals, status = status)
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
# Build and write the dictionary of one year.
|
| 192 |
+
build_year <- function(y, spec) {
|
| 193 |
+
sp <- spec[spec$year == y, ]
|
| 194 |
+
out <- list()
|
| 195 |
+
for (i in seq_len(nrow(sp))) {
|
| 196 |
+
m <- file.path(meta_dir, paste0(y, "__", sp$file[i], ".rds"))
|
| 197 |
+
if (!file.exists(m)) next
|
| 198 |
+
out[[length(out) + 1]] <- file_dictionary(readRDS(m), sp[i, ])
|
| 199 |
+
}
|
| 200 |
+
vars <- do.call(rbind, lapply(out, `[[`, "variables"))
|
| 201 |
+
vals <- do.call(rbind, lapply(out, `[[`, "values"))
|
| 202 |
+
# Variables without a label in their own program (e.g. the IDs of
|
| 203 |
+
# SAD_WGTS) take the label the same variable has in another file of the
|
| 204 |
+
# year; label_source records this.
|
| 205 |
+
nolab <- is.na(vars$label) | !nzchar(vars$label)
|
| 206 |
+
if (any(nolab)) {
|
| 207 |
+
lab_pool <- vars[!nolab & !duplicated(vars$variable), c("variable", "label", "file")]
|
| 208 |
+
k <- match(vars$variable[nolab], lab_pool$variable)
|
| 209 |
+
vars$label[nolab] <- lab_pool$label[k]
|
| 210 |
+
vars$label_source[nolab][!is.na(k)] <- paste("label of the same variable in", lab_pool$file[k[!is.na(k)]])
|
| 211 |
+
}
|
| 212 |
+
w <- vars$variable == "WTFA_SAD" & is.na(vars$label)
|
| 213 |
+
vars$label[w] <- "Weight for the 2010 Sample Adult file merged with the disability questions tests (sam_disb.sas)"
|
| 214 |
+
vars$label_source[w] <- "comment in the NCHS program sam_disb.sas"
|
| 215 |
+
dd <- file.path(out_dir, "data", y, "Dictionary")
|
| 216 |
+
vars$year <- as.integer(vars$year)
|
| 217 |
+
vals$year <- as.integer(vals$year)
|
| 218 |
+
write_parquet_clean(vars, file.path(dd, "VARIABLES.parquet"))
|
| 219 |
+
write_parquet_clean(vals, file.path(dd, "VALUES.parquet"))
|
| 220 |
+
st <- do.call(rbind, lapply(out, `[[`, "status"))
|
| 221 |
+
cat(sprintf(
|
| 222 |
+
"%d: %d files, %d variables (%d with codebook text), %d value rows (%d with published count)\n",
|
| 223 |
+
y, nrow(st), nrow(vars), sum(vars$in_codebook), nrow(vals), sum(st$values_with_published_count)
|
| 224 |
+
))
|
| 225 |
+
st
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
spec <- build_spec()
|
| 229 |
+
st <- do.call(rbind, parallel::mclapply(sort(unique(spec$year)), build_year,
|
| 230 |
+
spec = spec, mc.cores = 2, mc.preschedule = FALSE
|
| 231 |
+
))
|
| 232 |
+
utils::write.csv(st, file.path(log_dir, "dictionary_status.csv"), row.names = FALSE)
|
pipeline/05_validate.R
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# 05_validate.R: row counts, CSV cross-checks and published estimates
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Writes ../logs/validation.csv with one row per check:
|
| 5 |
+
# rows_vs_codebook file rows vs the record count printed in the NCHS
|
| 6 |
+
# documentation (1997-2003 codebook header "N RECORDS";
|
| 7 |
+
# 2004-2025 RECTYPE frequency at 100.00 percent in the
|
| 8 |
+
# *_freq.pdf / *-codebook.pdf)
|
| 9 |
+
# rows_vs_srvydesc 2019-2025 Sample Adult / Sample Child rows vs the
|
| 10 |
+
# interviewed counts in the 2025 Survey Description Table
|
| 11 |
+
# values_vs_codebook published unweighted frequencies vs data counts
|
| 12 |
+
# (from the dictionary, per file)
|
| 13 |
+
# csv_crosscheck 1997-2018 ASCII-derived Parquet vs the NCHS CSV copy
|
| 14 |
+
# (2015-2018), and 2019+ CSV-derived Parquet vs the ASCII
|
| 15 |
+
# copy (tolerance: the ASCII field rounding)
|
| 16 |
+
# layout fixed-width record length vs the SAS layout end column
|
| 17 |
+
# estimate published estimates reproduced with the survey package
|
| 18 |
+
# =============================================================================
|
| 19 |
+
source("00_config.R")
|
| 20 |
+
source("sas_setup.R")
|
| 21 |
+
source("files_spec.R")
|
| 22 |
+
source("codebook_pdf.R")
|
| 23 |
+
source("readers.R")
|
| 24 |
+
suppressMessages(library(arrow))
|
| 25 |
+
meta_dir <- file.path(log_dir, "meta")
|
| 26 |
+
spec <- build_spec()
|
| 27 |
+
cs <- utils::read.csv(file.path(log_dir, "convert_status.csv"), stringsAsFactors = FALSE)
|
| 28 |
+
checks <- list()
|
| 29 |
+
|
| 30 |
+
# Record one validation result.
|
| 31 |
+
add <- function(check, year, file, expected, observed, pass, source, note = "") {
|
| 32 |
+
checks[[length(checks) + 1]] <<- data.frame(
|
| 33 |
+
check = check, year = year, file = file, expected = as.character(expected),
|
| 34 |
+
observed = as.character(observed), pass = pass, source = source, note = note,
|
| 35 |
+
stringsAsFactors = FALSE
|
| 36 |
+
)
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
# ---- Row counts against NCHS documentation ----------------------------------
|
| 40 |
+
|
| 41 |
+
# Published record count of a data file from its documentation PDF.
|
| 42 |
+
published_records <- function(pdf) {
|
| 43 |
+
if (is.na(pdf) || !file.exists(pdf)) {
|
| 44 |
+
return(NA_real_)
|
| 45 |
+
}
|
| 46 |
+
x <- pdf_lines(pdf)
|
| 47 |
+
r <- regmatches(x, regexpr("[0-9][0-9,]* RECORDS", x))
|
| 48 |
+
if (length(r)) {
|
| 49 |
+
return(as.numeric(gsub("[^0-9]", "", r[1])))
|
| 50 |
+
}
|
| 51 |
+
hit <- grep("^\\s*[0-9]{2}\\s+[A-Za-z].*\\s([0-9][0-9,]*)\\s+100\\.00\\s*$", x, value = TRUE)
|
| 52 |
+
if (length(hit)) {
|
| 53 |
+
return(as.numeric(gsub(",", "", sub(".*\\s([0-9][0-9,]*)\\s+100\\.00\\s*$", "\\1", hit[1]))))
|
| 54 |
+
}
|
| 55 |
+
NA_real_
|
| 56 |
+
}
|
| 57 |
+
x_cat <- read_catalog()
|
| 58 |
+
docs <- x_cat[x_cat$kind %in% c("documentation", "program") & grepl("\\.pdf$", x_cat$file, ignore.case = TRUE), ]
|
| 59 |
+
for (i in seq_len(nrow(spec))) {
|
| 60 |
+
r <- spec[i, ]
|
| 61 |
+
if (r$stem == "MORT" || r$reader %in% c("sas7bdat", "revwts_csv") || r$singleton) next
|
| 62 |
+
st <- tolower(r$stem)
|
| 63 |
+
dd <- docs[docs$year == r$year, ]
|
| 64 |
+
pat <- if (r$year >= 2019) paste0("^", st, "-codebook\\.pdf$") else if (r$year <= 2003) paste0("^", st, "\\.pdf$") else paste0("^", st, "_freq\\.pdf$")
|
| 65 |
+
k <- grep(pat, dd$file, ignore.case = TRUE)
|
| 66 |
+
if (!length(k)) next
|
| 67 |
+
pub <- published_records(dd$raw[k[1]])
|
| 68 |
+
got <- cs$rows[cs$year == r$year & cs$file == r$file]
|
| 69 |
+
if (is.na(pub) || !length(got)) next
|
| 70 |
+
add("rows_vs_codebook", r$year, r$file, pub, got, pub == got, dd$url[k[1]])
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
# 2019-2025 interviewed Sample Adults / Children (2025 Survey Description,
|
| 74 |
+
# Table 2 of the 2024 document for 2019-2024 and of the 2025 document).
|
| 75 |
+
sd <- x_cat$raw[x_cat$year == 2024 & x_cat$file == "srvydesc-508.pdf"]
|
| 76 |
+
if (length(sd) && file.exists(sd)) {
|
| 77 |
+
x <- pdf_lines(sd)
|
| 78 |
+
for (y in 2019:2024) {
|
| 79 |
+
l <- grep(sprintf("^\\s*%d\\s+[0-9,]+\\s+[0-9,]+\\s+[0-9,]+\\s+[0-9,]+\\s+[0-9,]+\\s+[0-9,]+\\s+[0-9,]+\\s*$", y), x, value = TRUE)
|
| 80 |
+
if (!length(l)) next
|
| 81 |
+
n <- as.numeric(gsub(",", "", strsplit(squish(l[1]), " ")[[1]]))
|
| 82 |
+
for (z in list(c("ADULT", 6), c("CHILD", 8))) {
|
| 83 |
+
f <- sprintf("%s%02d", z[1], y %% 100)
|
| 84 |
+
# ADULT20 also holds the 2019 adults re-interviewed in 2020; the
|
| 85 |
+
# Table 2 count is the 2020 sample (ADULTPART20).
|
| 86 |
+
if (f == "ADULT20") f <- "ADULTPART20"
|
| 87 |
+
got <- cs$rows[cs$year == y & cs$file == f]
|
| 88 |
+
if (length(got)) {
|
| 89 |
+
add(
|
| 90 |
+
"rows_vs_srvydesc", y, f, n[as.integer(z[2])], got, n[as.integer(z[2])] == got,
|
| 91 |
+
x_cat$url[x_cat$year == 2024 & x_cat$file == "srvydesc-508.pdf"],
|
| 92 |
+
"Table 2, interviewed sample adults/children"
|
| 93 |
+
)
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
# ---- Published frequencies vs data (from the dictionary) --------------------
|
| 100 |
+
ds <- file.path(log_dir, "dictionary_status.csv")
|
| 101 |
+
if (file.exists(ds)) {
|
| 102 |
+
d <- utils::read.csv(ds, stringsAsFactors = FALSE)
|
| 103 |
+
d <- d[d$values_with_published_count > 0, ]
|
| 104 |
+
for (i in seq_len(nrow(d))) {
|
| 105 |
+
add(
|
| 106 |
+
"values_vs_codebook", d$year[i], d$file[i],
|
| 107 |
+
paste(d$values_with_published_count[i], "published counts"),
|
| 108 |
+
paste(d$published_count_mismatch[i], "differ from data"),
|
| 109 |
+
d$published_count_mismatch[i] == 0, d$codebook[i],
|
| 110 |
+
"count_published vs count_data in VALUES.parquet (codes present in both)"
|
| 111 |
+
)
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
# ---- Layout checks -----------------------------------------------------------
|
| 116 |
+
fw <- cs[cs$status == "ok" & !is.na(cs$layout_end), ]
|
| 117 |
+
for (i in seq_len(nrow(fw))) {
|
| 118 |
+
ok <- fw$record_length_max[i] <= fw$layout_end[i] && fw$unparsed_numeric[i] == 0
|
| 119 |
+
add(
|
| 120 |
+
"layout", fw$year[i], fw$file[i], paste("record length <=", fw$layout_end[i], "and no unparsable numbers"),
|
| 121 |
+
paste0("record length ", fw$record_length_min[i], "-", fw$record_length_max[i], "; unparsed ", fw$unparsed_numeric[i]),
|
| 122 |
+
ok, fw$program[i], fw$unparsed_vars[i]
|
| 123 |
+
)
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
# ---- CSV / ASCII cross-checks -------------------------------------------------
|
| 127 |
+
|
| 128 |
+
# Compare a Parquet table to another reading of the same file.
|
| 129 |
+
compare_tables <- function(a, b, key, tol) {
|
| 130 |
+
# Blank text is missing (as in the Parquet files) before matching keys.
|
| 131 |
+
for (v in key) b[[v]][!is.na(b[[v]]) & trimws(b[[v]]) == ""] <- NA
|
| 132 |
+
b <- b[match(do.call(paste, a[key]), do.call(paste, b[key])), , drop = FALSE]
|
| 133 |
+
common <- intersect(names(a), names(b))
|
| 134 |
+
bad <- 0
|
| 135 |
+
badv <- character()
|
| 136 |
+
for (v in common) {
|
| 137 |
+
x <- a[[v]]
|
| 138 |
+
y <- b[[v]]
|
| 139 |
+
if (is.character(x) || is.character(y)) {
|
| 140 |
+
x <- as.character(x)
|
| 141 |
+
y <- as.character(y)
|
| 142 |
+
y[!is.na(y) & trimws(y) == ""] <- NA
|
| 143 |
+
# A lone "." marks a missing character value in some ASCII files
|
| 144 |
+
# (e.g. 2021 PARADATA21 ONEFAM_FLG) where the CSV is blank.
|
| 145 |
+
x[!is.na(x) & x == "."] <- NA
|
| 146 |
+
y[!is.na(y) & y == "."] <- NA
|
| 147 |
+
n <- sum(xor(is.na(x), is.na(y)) | (!is.na(x) & !is.na(y) & trimws(x) != trimws(y)))
|
| 148 |
+
} else {
|
| 149 |
+
t <- if (is.function(tol)) tol(v) else tol
|
| 150 |
+
n <- sum(xor(is.na(x), is.na(y)) | (!is.na(x) & !is.na(y) & abs(x - y) > t))
|
| 151 |
+
}
|
| 152 |
+
if (n > 0) {
|
| 153 |
+
bad <- bad + n
|
| 154 |
+
badv <- c(badv, v)
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
list(
|
| 158 |
+
cells = bad, vars = badv, common = length(common),
|
| 159 |
+
only_a = setdiff(names(a), names(b)), only_b = setdiff(names(b), names(a))
|
| 160 |
+
)
|
| 161 |
+
}
|
| 162 |
+
csv_zip <- x_cat[grepl("csv\\.zip$", x_cat$file) & !grepl("revwts|pair", x_cat$file, ignore.case = TRUE), ]
|
| 163 |
+
td <- file.path(log_dir, "tmp", "validate")
|
| 164 |
+
dir.create(td, recursive = TRUE, showWarnings = FALSE)
|
| 165 |
+
for (y in 2015:2025) {
|
| 166 |
+
sp <- spec[spec$year == y & spec$component %in% c("Core", "Paradata", "Supplement", "Injury", "Longitudinal", "ImputedIncome") & !spec$singleton, ]
|
| 167 |
+
for (i in seq_len(nrow(sp))) {
|
| 168 |
+
r <- sp[i, ]
|
| 169 |
+
pq <- file.path(out_dir, r$path)
|
| 170 |
+
if (!file.exists(pq)) next
|
| 171 |
+
a <- as.data.frame(read_parquet(pq))
|
| 172 |
+
key <- intersect(c("HHX", "FMX", "FPX", "PX", "IMPNUM", "IMPNUM_A", "IMPNUM_C", names(a)[grepl("EPNO|EPN$|^EPISODE", names(a))]), names(a))
|
| 173 |
+
if (y >= 2019) {
|
| 174 |
+
# 2019+: compare with the ASCII copy read through the SAS layout.
|
| 175 |
+
asc <- x_cat[x_cat$year == y & tolower(x_cat$file) == tolower(sub("csv\\.zip$", ".zip", basename(r$archive))), ]
|
| 176 |
+
if (!nrow(asc)) next
|
| 177 |
+
mem <- utils::unzip(asc$raw[1], list = TRUE)$Name
|
| 178 |
+
mem <- mem[grepl("\\.dat$", mem, ignore.case = TRUE)][1]
|
| 179 |
+
utils::unzip(asc$raw[1], files = mem, exdir = td, junkpaths = TRUE)
|
| 180 |
+
lay <- program_layout(r$program, r$section)$layout
|
| 181 |
+
b <- read_fixed(file.path(td, basename(mem)), lay)$data
|
| 182 |
+
unlink(file.path(td, basename(mem)))
|
| 183 |
+
# Allowed difference: half a unit of the last digit the ASCII field holds.
|
| 184 |
+
tol <- function(v) {
|
| 185 |
+
d <- lay$decimals[lay$variable == v]
|
| 186 |
+
w <- lay$width[lay$variable == v]
|
| 187 |
+
# A field of width w holding a value with more digits than fit
|
| 188 |
+
# is rounded by NCHS; allow half a unit of the last printed digit.
|
| 189 |
+
if (!length(d)) 1e-9 else max(10^-d / 2, 10^(-max(0, w - 1 - nchar(format(floor(max(abs(a[[v]]), na.rm = TRUE)), scientific = FALSE)))) / 2) + 1e-9
|
| 190 |
+
}
|
| 191 |
+
res <- compare_tables(a, b, key, tol)
|
| 192 |
+
src <- asc$url[1]
|
| 193 |
+
what <- "CSV-derived Parquet vs NCHS ASCII (+/- ASCII rounding)"
|
| 194 |
+
} else {
|
| 195 |
+
cz <- csv_zip[csv_zip$year == y, ]
|
| 196 |
+
cz <- cz[tolower(sub("csv\\.zip$", "", cz$file)) == tolower(r$stem) |
|
| 197 |
+
tolower(sub("csv\\.zip$", "", cz$file)) == tolower(r$file), ]
|
| 198 |
+
if (!nrow(cz)) {
|
| 199 |
+
# 2015: the CSV is inside the same ZIP as the ASCII file.
|
| 200 |
+
inner <- utils::unzip(r$archive, list = TRUE)$Name
|
| 201 |
+
inner <- inner[grepl("\\.csv$", inner, ignore.case = TRUE)]
|
| 202 |
+
if (!length(inner)) next
|
| 203 |
+
zf <- r$archive
|
| 204 |
+
src <- r$source_url
|
| 205 |
+
} else {
|
| 206 |
+
zf <- cz$raw[1]
|
| 207 |
+
inner <- utils::unzip(zf, list = TRUE)$Name
|
| 208 |
+
inner <- inner[grepl("\\.csv$", inner, ignore.case = TRUE)]
|
| 209 |
+
src <- cz$url[1]
|
| 210 |
+
}
|
| 211 |
+
utils::unzip(zf, files = inner[1], exdir = td, junkpaths = TRUE)
|
| 212 |
+
b <- utils::read.csv(file.path(td, basename(inner[1])), colClasses = "character", check.names = FALSE)
|
| 213 |
+
unlink(file.path(td, basename(inner[1])))
|
| 214 |
+
names(b) <- toupper(names(b))
|
| 215 |
+
for (v in names(b)) if (v %in% names(a) && !is.character(a[[v]])) b[[v]] <- suppressWarnings(as.numeric(b[[v]]))
|
| 216 |
+
# NCHS CSV copies store implied-decimal fields unscaled (BMI 2358
|
| 217 |
+
# for 23.58); scale them by the SAS INPUT decimals to compare.
|
| 218 |
+
lay <- program_layout(r$program, r$section)$layout
|
| 219 |
+
scaled <- character()
|
| 220 |
+
for (j in which(lay$decimals > 0 & lay$variable %in% names(b))) {
|
| 221 |
+
vv <- lay$variable[j]
|
| 222 |
+
if (!any(grepl(".", b[[vv]][!is.na(b[[vv]])], fixed = TRUE))) {
|
| 223 |
+
b[[vv]] <- b[[vv]] / 10^lay$decimals[j]
|
| 224 |
+
scaled <- c(scaled, vv)
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
res <- compare_tables(a, b, key, 1e-6)
|
| 228 |
+
what <- paste0(
|
| 229 |
+
"ASCII-derived Parquet vs NCHS CSV copy",
|
| 230 |
+
if (length(scaled)) paste0(" (CSV stores implied-decimal fields unscaled: ", paste(scaled, collapse = " "), ")") else ""
|
| 231 |
+
)
|
| 232 |
+
# 2016: the ASCII Sample Child file carries the revised 2016
|
| 233 |
+
# weights (equal to SAMCHILD_REVWTS); the CSV copy has the original.
|
| 234 |
+
if (res$cells > 0 && y == 2016 && all(res$vars %in% c("WTIA_SC", "WTFA_SC", "WTIA", "WTFA", "WTIA_SA", "WTFA_SA"))) {
|
| 235 |
+
rw <- file.path(out_dir, spec$path[spec$year == 2016 & spec$file == paste0(r$stem, "_REVWTS")][1])
|
| 236 |
+
if (length(rw) && file.exists(rw)) {
|
| 237 |
+
rv <- as.data.frame(read_parquet(rw))
|
| 238 |
+
chk <- compare_tables(a[intersect(names(a), names(rv))], rv, intersect(key, names(rv)), 1e-6)
|
| 239 |
+
if (chk$cells == 0) {
|
| 240 |
+
what <- paste(what, "; the differing weights equal the NCHS revised 2016 weights", basename(rw), "(the CSV copy has the original weights)")
|
| 241 |
+
res$cells <- 0
|
| 242 |
+
}
|
| 243 |
+
}
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
add(
|
| 247 |
+
"csv_crosscheck", y, r$file, paste(res$common, "common columns, 0 differing cells"),
|
| 248 |
+
paste(res$cells, "differing cells", if (length(res$vars)) paste0("(", paste(utils::head(res$vars, 5), collapse = " "), ")") else ""),
|
| 249 |
+
res$cells == 0, src,
|
| 250 |
+
paste(what, if (length(res$only_a) + length(res$only_b)) paste("; columns only in one copy:", length(res$only_a), "/", length(res$only_b)) else "")
|
| 251 |
+
)
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
# ---- Linked mortality vs person files ---------------------------------------------
|
| 256 |
+
# Every mortality record should match one person of the same year's PERSONSX
|
| 257 |
+
# through PUBLICID = SRVY_YR + HHX + FMX + FPX (PX through 2003).
|
| 258 |
+
for (y in sort(unique(spec$year[spec$stem == "MORT"]))) {
|
| 259 |
+
mp <- file.path(out_dir, spec$path[spec$year == y & spec$stem == "MORT"][1])
|
| 260 |
+
pp <- file.path(out_dir, spec$path[spec$year == y & spec$stem == "PERSONSX" & spec$component == "Core"][1])
|
| 261 |
+
if (!file.exists(mp) || !file.exists(pp)) next
|
| 262 |
+
mo <- read_parquet(mp, col_select = "PUBLICID")$PUBLICID
|
| 263 |
+
pe <- as.data.frame(read_parquet(pp))
|
| 264 |
+
pn <- if ("FPX" %in% names(pe)) pe$FPX else pe$PX
|
| 265 |
+
id <- paste0(pe$SRVY_YR, pe$HHX, pe$FMX, pn)
|
| 266 |
+
add(
|
| 267 |
+
"mortality_link", y, basename(mp), "every PUBLICID found in PERSONSX, no duplicates",
|
| 268 |
+
paste0(length(mo), " records, ", sum(mo %in% id), " matched (PERSONSX ", length(id), " persons)"),
|
| 269 |
+
all(mo %in% id) && !anyDuplicated(mo), "PERSONSX of the same year",
|
| 270 |
+
"PUBLICID = SRVY_YR || HHX || FMX || FPX (PX through 2003)"
|
| 271 |
+
)
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
# ---- Published estimates -------------------------------------------------------
|
| 275 |
+
|
| 276 |
+
# Weighted percentage with a Taylor-series SE (WR design, as NCHS documents).
|
| 277 |
+
svy_pct <- function(d, y, w, strata, psu) {
|
| 278 |
+
des <- survey::svydesign(ids = stats::as.formula(paste0("~", psu)), strata = stats::as.formula(paste0("~", strata)), weights = stats::as.formula(paste0("~", w)), nest = TRUE, data = d)
|
| 279 |
+
m <- survey::svymean(stats::as.formula(paste0("~", y)), des, na.rm = TRUE)
|
| 280 |
+
c(est = 100 * unname(stats::coef(m)), se = 100 * unname(survey::SE(m)))
|
| 281 |
+
}
|
| 282 |
+
options(survey.lonely.psu = "adjust")
|
| 283 |
+
est <- list(
|
| 284 |
+
list(
|
| 285 |
+
year = 2019, file = "data/2019/Core/ADULT19.parquet", w = "WTFA_A", s = "PSTRAT", p = "PPSU",
|
| 286 |
+
def = function(d) {
|
| 287 |
+
d <- d[d$SMKCIGST_A %in% 1:4, ]
|
| 288 |
+
d$y <- as.numeric(d$SMKCIGST_A %in% 1:2)
|
| 289 |
+
d
|
| 290 |
+
}, target = 14.0,
|
| 291 |
+
what = "Current cigarette smoking, adults 18+, 2019 (SMKCIGST_A in 1,2; unknown status excluded)",
|
| 292 |
+
src = "Cornelius ME et al. MMWR 2020;69(46):1736-1742 (14.0%)"
|
| 293 |
+
),
|
| 294 |
+
list(
|
| 295 |
+
year = 2018, file = "data/2018/Core/SAMADULT.parquet", w = "WTFA_SA", s = "PSTRAT", p = "PPSU",
|
| 296 |
+
def = function(d) {
|
| 297 |
+
d <- d[d$SMKSTAT2 %in% 1:4, ]
|
| 298 |
+
d$y <- as.numeric(d$SMKSTAT2 %in% 1:2)
|
| 299 |
+
d
|
| 300 |
+
}, target = 13.7,
|
| 301 |
+
what = "Current cigarette smoking, adults 18+, 2018 (SMKSTAT2 in 1,2; unknown status excluded)",
|
| 302 |
+
src = "Creamer MR et al. MMWR 2019;68(45):1013-1019 (13.7%)"
|
| 303 |
+
),
|
| 304 |
+
list(
|
| 305 |
+
year = 2010, file = "data/2010/Core/SAMADULT.parquet", w = "WTFA_SA", s = "STRAT_P", p = "PSU_P",
|
| 306 |
+
def = function(d) {
|
| 307 |
+
d <- d[d$SMKSTAT2 %in% 1:4, ]
|
| 308 |
+
d$y <- as.numeric(d$SMKSTAT2 %in% 1:2)
|
| 309 |
+
d
|
| 310 |
+
}, target = 19.3,
|
| 311 |
+
what = "Current cigarette smoking, adults 18+, 2010 (SMKSTAT2 in 1,2; unknown status excluded)",
|
| 312 |
+
src = "CDC. Vital signs: current cigarette smoking among adults aged >=18 years. MMWR 2011;60(35):1207-1212 (19.3%)"
|
| 313 |
+
),
|
| 314 |
+
list(
|
| 315 |
+
year = 2005, file = "data/2005/Core/SAMADULT.parquet", w = "WTFA_SA", s = "STRATUM", p = "PSU",
|
| 316 |
+
def = function(d) {
|
| 317 |
+
d <- d[d$SMKSTAT2 %in% 1:4, ]
|
| 318 |
+
d$y <- as.numeric(d$SMKSTAT2 %in% 1:2)
|
| 319 |
+
d
|
| 320 |
+
}, target = 20.9,
|
| 321 |
+
what = "Current cigarette smoking, adults 18+, 2005 (SMKSTAT2 in 1,2; unknown status excluded)",
|
| 322 |
+
src = "CDC. Tobacco use among adults - United States, 2005. MMWR 2006;55(42):1145-1148 (20.9%)"
|
| 323 |
+
)
|
| 324 |
+
)
|
| 325 |
+
for (e in est) {
|
| 326 |
+
pq <- file.path(out_dir, e$file)
|
| 327 |
+
if (!file.exists(pq)) next
|
| 328 |
+
d <- as.data.frame(read_parquet(pq))
|
| 329 |
+
if (!all(c(e$s, e$p) %in% names(d))) {
|
| 330 |
+
e$s <- intersect(c("PSTRAT", "STRAT_P"), names(d))[1]
|
| 331 |
+
e$p <- intersect(c("PPSU", "PSU_P"), names(d))[1]
|
| 332 |
+
}
|
| 333 |
+
d <- e$def(d)
|
| 334 |
+
r <- svy_pct(d, "y", e$w, e$s, e$p)
|
| 335 |
+
add(
|
| 336 |
+
"estimate", e$year, basename(e$file), sprintf("%.1f%%", e$target),
|
| 337 |
+
sprintf("%.2f%% (SE %.2f)", r["est"], r["se"]), abs(r["est"] - e$target) < 0.05 + 1e-9,
|
| 338 |
+
e$src, paste(e$what, "; design", e$s, e$p, e$w)
|
| 339 |
+
)
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
v <- do.call(rbind, checks)
|
| 343 |
+
utils::write.csv(v, file.path(log_dir, "validation.csv"), row.names = FALSE)
|
| 344 |
+
write_parquet_clean(v, file.path(out_dir, "metadata", "VALIDATION.parquet"))
|
| 345 |
+
print(table(v$check, v$pass, useNA = "ifany"))
|
| 346 |
+
print(utils::head(v[!v$pass, ], 40))
|
pipeline/06_manifest.R
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# 06_manifest.R: file catalogue and year table for the Hugging Face dataset
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# ../parquet/metadata/FILES.parquet one row per Parquet file: year,
|
| 5 |
+
# component, NCHS file name, file type (stem), label, rows, columns, grain,
|
| 6 |
+
# join keys, design variables present, path, hf_url, sizes, source URL,
|
| 7 |
+
# ZIP member, SAS program used for the layout, MD5 of the source file.
|
| 8 |
+
# ../parquet/metadata/YEARS.parquet one row per survey year: questionnaire
|
| 9 |
+
# era, sample design period, file counts, persons / sample adults /
|
| 10 |
+
# sample children, strata / PSU / weight variables and pooling guidance.
|
| 11 |
+
# =============================================================================
|
| 12 |
+
source("00_config.R")
|
| 13 |
+
source("files_spec.R")
|
| 14 |
+
suppressMessages(library(arrow))
|
| 15 |
+
meta <- list.files(file.path(log_dir, "meta"), pattern = "\\.rds$", full.names = TRUE)
|
| 16 |
+
mt <- lapply(meta, readRDS)
|
| 17 |
+
m <- do.call(rbind, lapply(mt, `[[`, "manifest"))
|
| 18 |
+
cols <- lapply(mt, function(z) z$columns$variable)
|
| 19 |
+
names(cols) <- m$path
|
| 20 |
+
o <- order(m$year, m$component, m$file)
|
| 21 |
+
m <- m[o, ]
|
| 22 |
+
spec <- build_spec()
|
| 23 |
+
|
| 24 |
+
# Plain-language label of each NCHS file type.
|
| 25 |
+
stem_labels <- c(
|
| 26 |
+
HOUSEHLD = "Household file", FAMILYXX = "Family file", PERSONSX = "Person file",
|
| 27 |
+
SAMADULT = "Sample Adult file", SAMCHILD = "Sample Child file",
|
| 28 |
+
ADULT = "Sample Adult file (2019+ redesign)", CHILD = "Sample Child file (2019+ redesign)",
|
| 29 |
+
ADULTINC = "Sample Adult imputed income (10 implicates, stacked)",
|
| 30 |
+
CHILDINC = "Sample Child imputed income (10 implicates, stacked)",
|
| 31 |
+
ADULTLONG = "2019-2020 longitudinal Sample Adult IDs and weight (WTSA_L)",
|
| 32 |
+
ADULTPART = "2020 partial-sample Sample Adult IDs and weight for pooled 2019-2020 (WTSA_P)",
|
| 33 |
+
PARADATA = "Paradata (interview process) file", INJEPSOD = "Injury episode file",
|
| 34 |
+
POIEPSOD = "Poisoning episode file", INJPOIEP = "Injury/poisoning episode file",
|
| 35 |
+
INJVERBT = "Injury/poisoning verbatim file", IMMUNIZE = "Immunization file (children)",
|
| 36 |
+
INCMIMP = "Imputed family income / personal earnings (one implicate)",
|
| 37 |
+
INCIMPS = "Supplemental imputed income, top-coded (one implicate)",
|
| 38 |
+
ALTHEALT = "Adult complementary and alternative medicine supplement",
|
| 39 |
+
ALTVERBT = "Adult alternative medicine verbatim file", CHILDCAM = "Child complementary and alternative medicine supplement",
|
| 40 |
+
CANCERXX = "Cancer control supplement", PREGSMKG = "Pregnancy and smoking supplement",
|
| 41 |
+
PREVADLT = "Sample Adult prevention supplement", PREVCHLD = "Sample Child prevention supplement",
|
| 42 |
+
DISBTEST = "Disability questions tests", QUALLIFE = "Quality of life supplement",
|
| 43 |
+
ADLTDISB = "Adult disability supplement", CHLDDISB = "Child disability supplement",
|
| 44 |
+
FMLYDISB = "Family disability questions", FUNCDISB = "Functioning and disability supplement",
|
| 45 |
+
RATCAT = "Corrected family poverty ratio (RAT_CAT3) for 2007",
|
| 46 |
+
SC_BWT = "Sample Child birth weight file", SAD_WGTS = "Weights for Sample Adult merged with the 2010 disability tests",
|
| 47 |
+
REVWTS = "Revised 2016 weights", FINAL_PAIR_WEIGHT = "Parent-child pair weights",
|
| 48 |
+
MORT = "Public-use linked mortality file (NDI follow-up through 31 December 2019)"
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Grain (smallest unique ID combination, checked on the data) and join keys
|
| 52 |
+
# (all record identifiers of the file: HHX, FMX, FPX/PX, episode or implicate
|
| 53 |
+
# number; SRVY_YR where a file spans two survey years, e.g. 2009 DISBTEST).
|
| 54 |
+
grain_keys <- function(path, cn, stem) {
|
| 55 |
+
if (stem == "MORT") {
|
| 56 |
+
return(c("one row per PUBLICID", "PUBLICID"))
|
| 57 |
+
}
|
| 58 |
+
ids <- intersect(c("HHX", "HHX_2019", "HHX_2020", "FMX", "FPX", "PX"), cn)
|
| 59 |
+
if (!length(ids)) {
|
| 60 |
+
return(c("reference table", ""))
|
| 61 |
+
}
|
| 62 |
+
extra <- cn[grepl("EPNO$|^IMPNUM|^IMRESPNO$", cn)]
|
| 63 |
+
if (stem %in% c("ADULT", "CHILD")) extra <- character() # one implicate column, not a key
|
| 64 |
+
d <- as.data.frame(read_parquet(file.path(out_dir, path), col_select = dplyr::all_of(c(ids, extra, intersect("SRVY_YR", cn)))))
|
| 65 |
+
full <- c(ids, extra)
|
| 66 |
+
if (anyDuplicated(d[full]) && "SRVY_YR" %in% cn) full <- c("SRVY_YR", full)
|
| 67 |
+
keys <- paste(full, collapse = " + ")
|
| 68 |
+
for (k in seq_along(full)) {
|
| 69 |
+
g <- full[seq_len(k)]
|
| 70 |
+
if (!anyDuplicated(d[g])) {
|
| 71 |
+
return(c(paste("one row per", paste(g, collapse = " + ")), keys))
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
c(paste("several rows per", keys), keys)
|
| 75 |
+
}
|
| 76 |
+
gk <- t(mapply(grain_keys, m$path, cols[m$path], m$stem))
|
| 77 |
+
m$grain <- gk[, 1]
|
| 78 |
+
m$join_keys <- gk[, 2]
|
| 79 |
+
# Design variables (strata, PSU, weights) among the columns of a file.
|
| 80 |
+
design_like <- function(cn) {
|
| 81 |
+
paste(cn[grepl("^(STRATUM|PSU|STRAT_P|PSU_P|PSTRAT|PPSU|WT[A-Z0-9_]*|WGT_NEW|SA_WGT_NEW|FINAL_PAIR_WEIGHT)$", cn, ignore.case = TRUE)], collapse = " ")
|
| 82 |
+
}
|
| 83 |
+
m$design_variables <- vapply(cols[m$path], design_like, "")
|
| 84 |
+
m$label <- unname(stem_labels[m$stem])
|
| 85 |
+
m$label[m$component == "Design" & grepl("^[0-9]{4}", m$file)] <- paste(
|
| 86 |
+
"Supplemental dummy records for singleton PSUs (layout of", m$stem[m$component == "Design" & grepl("^[0-9]{4}", m$file)], "file)"
|
| 87 |
+
)
|
| 88 |
+
m$hf_url <- paste0("hf://datasets/jamesjiadazhan/NHIS/", m$path)
|
| 89 |
+
m$doc_url <- spec_doc <- vapply(seq_len(nrow(m)), function(i) {
|
| 90 |
+
s <- spec[spec$year == m$year[i] & spec$file == m$file[i], ]
|
| 91 |
+
if (!nrow(s) || is.na(s$doc[1])) "" else paste0(ftp, nchs, "/", sub(paste0(raw_dir, "/"), "", s$doc[1]))
|
| 92 |
+
}, "")
|
| 93 |
+
m$year <- as.integer(m$year)
|
| 94 |
+
m$rows <- as.integer(m$rows)
|
| 95 |
+
m$columns <- as.integer(m$columns)
|
| 96 |
+
dir.create(file.path(out_dir, "metadata"), showWarnings = FALSE)
|
| 97 |
+
files <- m[c(
|
| 98 |
+
"year", "component", "file", "stem", "label", "rows", "columns", "grain", "join_keys",
|
| 99 |
+
"design_variables", "path", "hf_url", "parquet_bytes", "source_url", "member", "program",
|
| 100 |
+
"layout_note", "doc_url", "source_md5"
|
| 101 |
+
)]
|
| 102 |
+
write_parquet_clean(files, file.path(out_dir, "metadata", "FILES.parquet"))
|
| 103 |
+
|
| 104 |
+
# ---- Year table ------------------------------------------------------------------
|
| 105 |
+
yr <- data.frame(year = sort(unique(m$year)))
|
| 106 |
+
# Rows of the core file of a given type in year y.
|
| 107 |
+
pick <- function(y, stems) {
|
| 108 |
+
k <- m$year == y & m$stem %in% stems & m$component %in% c("Core")
|
| 109 |
+
if (any(k)) m$rows[k][1] else NA_integer_
|
| 110 |
+
}
|
| 111 |
+
yr$questionnaire <- ifelse(yr$year <= 2018, "1997-2018 design (household, family, person, sample adult/child files)", "2019+ redesign (sample adult, sample child files)")
|
| 112 |
+
yr$sample_design_period <- ifelse(yr$year <= 2005, "1995-2005", ifelse(yr$year <= 2015, "2006-2015", ifelse(yr$year <= 2024, "2016-2024", "2025+")))
|
| 113 |
+
yr$files <- as.integer(table(m$year)[as.character(yr$year)])
|
| 114 |
+
yr$households <- vapply(yr$year, pick, 1L, stems = "HOUSEHLD")
|
| 115 |
+
yr$families <- vapply(yr$year, pick, 1L, stems = "FAMILYXX")
|
| 116 |
+
yr$persons <- vapply(yr$year, pick, 1L, stems = "PERSONSX")
|
| 117 |
+
yr$sample_adults <- vapply(yr$year, pick, 1L, stems = c("SAMADULT", "ADULT"))
|
| 118 |
+
yr$sample_children <- vapply(yr$year, pick, 1L, stems = c("SAMCHILD", "CHILD"))
|
| 119 |
+
# Column names of the file of a given type in year y.
|
| 120 |
+
core_cols <- function(y, stem) {
|
| 121 |
+
k <- which(m$year == y & m$stem == stem)
|
| 122 |
+
if (length(k)) cols[[m$path[k[1]]]] else character()
|
| 123 |
+
}
|
| 124 |
+
# First candidate name present among the columns (NA if none).
|
| 125 |
+
first_in <- function(cn, cand) {
|
| 126 |
+
z <- intersect(cand, cn)
|
| 127 |
+
if (length(z)) z[1] else NA_character_
|
| 128 |
+
}
|
| 129 |
+
yr$strata <- vapply(yr$year, function(y) first_in(c(core_cols(y, "PERSONSX"), core_cols(y, "ADULT")), c("STRATUM", "STRAT_P", "PSTRAT")), "")
|
| 130 |
+
yr$psu <- vapply(yr$year, function(y) first_in(c(core_cols(y, "PERSONSX"), core_cols(y, "ADULT")), c("PSU", "PSU_P", "PPSU")), "")
|
| 131 |
+
yr$weight_household <- vapply(yr$year, function(y) first_in(core_cols(y, "HOUSEHLD"), "WTFA_HH"), "")
|
| 132 |
+
yr$weight_family <- vapply(yr$year, function(y) first_in(core_cols(y, "FAMILYXX"), "WTFA_FAM"), "")
|
| 133 |
+
yr$weight_person <- vapply(yr$year, function(y) first_in(core_cols(y, "PERSONSX"), "WTFA"), "")
|
| 134 |
+
yr$weight_sample_adult <- vapply(yr$year, function(y) first_in(c(core_cols(y, "SAMADULT"), core_cols(y, "ADULT")), c("WTFA_SA", "WTFA_A")), "")
|
| 135 |
+
yr$weight_sample_child <- vapply(yr$year, function(y) first_in(c(core_cols(y, "SAMCHILD"), core_cols(y, "CHILD")), c("WTFA_SC", "WTFA_C")), "")
|
| 136 |
+
yr$other_weights <- vapply(yr$year, function(y) {
|
| 137 |
+
k <- m$year == y & !m$stem %in% c("HOUSEHLD", "FAMILYXX", "PERSONSX", "SAMADULT", "SAMCHILD", "ADULT", "CHILD")
|
| 138 |
+
w <- unique(unlist(lapply(which(k), function(i) {
|
| 139 |
+
z <- strsplit(m$design_variables[i], " ")[[1]]
|
| 140 |
+
z <- z[grepl("^WT|WGT|PAIR", z, ignore.case = TRUE)]
|
| 141 |
+
if (length(z)) paste0(z, " (", m$file[i], ")")
|
| 142 |
+
})))
|
| 143 |
+
paste(w, collapse = "; ")
|
| 144 |
+
}, "")
|
| 145 |
+
yr$linked_mortality <- yr$year %in% m$year[m$stem == "MORT"]
|
| 146 |
+
yr$pooling_guidance <- ifelse(
|
| 147 |
+
yr$year <= 2005,
|
| 148 |
+
"Same design period 1997-2005 (STRATUM/PSU): pool as one sample with weights divided by the number of years. Pooling with 2006+ crosses a design change: make strata distinct (e.g. add 1000 x period) and treat periods as independent.",
|
| 149 |
+
ifelse(yr$year <= 2015,
|
| 150 |
+
"Same design period 2006-2015 (STRAT_P/PSU_P): pool as one sample with weights divided by the number of years. Pooling with 2005- or 2016+ crosses a design change: make strata distinct (e.g. add 1000 to PSTRAT) and treat periods as independent.",
|
| 151 |
+
ifelse(yr$year <= 2018,
|
| 152 |
+
"Design period 2016-2024 (PSTRAT/PPSU): pool 2016-2018 as one sample with weights divided by the number of years; pooling with 2015 or earlier needs distinct strata (e.g. add 1000 to PSTRAT) and independent periods. The 2019 redesign changed questionnaire, files and weighting: NCHS gives no public-use recipe for pooling 2016-2018 with 2019+ files, harmonise variables with care.",
|
| 153 |
+
"Pool any public-use years from 2019 on (including 2025) with PSTRAT/PPSU directly and weights divided by the number of years (NCHS 2025 Survey Description: no adjustment for the 2025 sample redesign is needed for public-use files). Use WTSA_P (ADULTPART20) for pooled 2019-2020 Sample Adult estimates."
|
| 154 |
+
)
|
| 155 |
+
)
|
| 156 |
+
)
|
| 157 |
+
write_parquet_clean(yr, file.path(out_dir, "metadata", "YEARS.parquet"))
|
| 158 |
+
options(width = 200)
|
| 159 |
+
print(yr[c("year", "files", "persons", "sample_adults", "sample_children", "strata", "psu", "weight_sample_adult")])
|
| 160 |
+
cat("files:", nrow(m), " rows:", sum(m$rows), " parquet GB:", round(sum(m$parquet_bytes) / 2^30, 2), "\n")
|
| 161 |
+
print(table(m$component))
|
| 162 |
+
print(table(m$grain[grepl("several", m$grain)]))
|
| 163 |
+
|
| 164 |
+
# ---- Hugging Face configs (hf_configs.yaml) -----------------------------------
|
| 165 |
+
# Dictionaries split by year, plus schema-stable tables: linked mortality
|
| 166 |
+
# (1997-2018) and parent-child pair weights (2019+).
|
| 167 |
+
cfg <- c("configs:")
|
| 168 |
+
# YAML lines of one Hugging Face config with one split per file.
|
| 169 |
+
add_cfg <- function(name, paths, splits) {
|
| 170 |
+
out <- c(paste0("- config_name: ", name), " data_files:")
|
| 171 |
+
for (i in seq_along(paths)) out <- c(out, paste0(" - split: ", splits[i]), paste0(" path: ", paths[i]))
|
| 172 |
+
out
|
| 173 |
+
}
|
| 174 |
+
cfg <- c(cfg, add_cfg("files", "metadata/FILES.parquet", "all"), add_cfg("years", "metadata/YEARS.parquet", "all"))
|
| 175 |
+
ys <- yr$year
|
| 176 |
+
cfg <- c(cfg, add_cfg("dictionary_variables", sprintf("data/%d/Dictionary/VARIABLES.parquet", ys), paste0("year_", ys)))
|
| 177 |
+
cfg <- c(cfg, add_cfg("dictionary_values", sprintf("data/%d/Dictionary/VALUES.parquet", ys), paste0("year_", ys)))
|
| 178 |
+
mo <- m[m$stem == "MORT", ]
|
| 179 |
+
cfg <- c(cfg, add_cfg("linked_mortality", mo$path, paste0("year_", mo$year)))
|
| 180 |
+
pw <- m[m$stem == "FINAL_PAIR_WEIGHT", ]
|
| 181 |
+
cfg <- c(cfg, add_cfg("pair_weights", pw$path, paste0("year_", pw$year)))
|
| 182 |
+
writeLines(cfg, "hf_configs.yaml")
|
pipeline/07_upload.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""07_upload.py: publish ../parquet to the public Hugging Face dataset.
|
| 2 |
+
|
| 3 |
+
Assembles README.md (YAML header + hf_configs.yaml + hf_dataset_card_body.md),
|
| 4 |
+
copies the pipeline scripts into parquet/pipeline/, creates the public dataset
|
| 5 |
+
repo if needed and uploads with upload_large_folder (resumable). Only Parquet
|
| 6 |
+
files, README and the pipeline scripts are uploaded (never raw/ or logs/).
|
| 7 |
+
The token is read from the CSV given by --token-csv (row "HuggingFace") and
|
| 8 |
+
is never printed or written to disk. With --dry-run the token is optional
|
| 9 |
+
and nothing is uploaded (README and pipeline copy are still assembled).
|
| 10 |
+
Usage: python3 -I 07_upload.py [--token-csv PATH] [--repo jamesjiadazhan/NHIS] [--dry-run]
|
| 11 |
+
Adapted from ../../NHANES/pipeline/07_upload.py.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import csv
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
|
| 18 |
+
ap = argparse.ArgumentParser()
|
| 19 |
+
ap.add_argument("--token-csv")
|
| 20 |
+
ap.add_argument("--repo", default="jamesjiadazhan/NHIS")
|
| 21 |
+
ap.add_argument("--dry-run", action="store_true")
|
| 22 |
+
a = ap.parse_args()
|
| 23 |
+
|
| 24 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 25 |
+
out = os.path.join(here, "..", "parquet")
|
| 26 |
+
|
| 27 |
+
header = """---
|
| 28 |
+
license: cc0-1.0
|
| 29 |
+
language:
|
| 30 |
+
- en
|
| 31 |
+
pretty_name: NHIS 1997-2025 (Parquet, dictionaries, linked mortality)
|
| 32 |
+
tags:
|
| 33 |
+
- nhis
|
| 34 |
+
- cdc
|
| 35 |
+
- nchs
|
| 36 |
+
- health
|
| 37 |
+
- epidemiology
|
| 38 |
+
- survey
|
| 39 |
+
- public-health
|
| 40 |
+
- mortality
|
| 41 |
+
- parquet
|
| 42 |
+
- duckdb
|
| 43 |
+
size_categories:
|
| 44 |
+
- 10M<n<100M
|
| 45 |
+
task_categories:
|
| 46 |
+
- tabular-classification
|
| 47 |
+
- tabular-regression
|
| 48 |
+
"""
|
| 49 |
+
with open(os.path.join(here, "hf_configs.yaml")) as f:
|
| 50 |
+
configs = f.read()
|
| 51 |
+
with open(os.path.join(here, "hf_dataset_card_body.md")) as f:
|
| 52 |
+
body = f.read()
|
| 53 |
+
with open(os.path.join(out, "README.md"), "w") as f:
|
| 54 |
+
f.write(header + configs + "---\n\n" + body)
|
| 55 |
+
|
| 56 |
+
pipe = os.path.join(out, "pipeline")
|
| 57 |
+
os.makedirs(pipe, exist_ok=True)
|
| 58 |
+
for n in sorted(os.listdir(here)):
|
| 59 |
+
if n.endswith((".R", ".py", ".yaml", ".md")):
|
| 60 |
+
shutil.copy2(os.path.join(here, n), os.path.join(pipe, n))
|
| 61 |
+
shutil.copy2(os.path.join(here, "..", "catalog_ftp_listing.csv"), os.path.join(pipe, "catalog_ftp_listing.csv"))
|
| 62 |
+
|
| 63 |
+
token = None
|
| 64 |
+
if a.token_csv:
|
| 65 |
+
with open(a.token_csv, encoding="utf-8-sig") as f:
|
| 66 |
+
for row in csv.reader(f):
|
| 67 |
+
if row and row[0].strip().lower() == "huggingface":
|
| 68 |
+
token = row[1].strip()
|
| 69 |
+
|
| 70 |
+
files = [os.path.join(r, n) for r, _, ns in os.walk(out) for n in ns]
|
| 71 |
+
files = [p for p in files if not p.endswith((".tmp", ".DS_Store"))]
|
| 72 |
+
print(f"{len(files)} files, {sum(os.path.getsize(p) for p in files) / 2**30:.2f} GB")
|
| 73 |
+
if a.dry_run:
|
| 74 |
+
print("dry run: nothing uploaded; repo", a.repo)
|
| 75 |
+
raise SystemExit(0)
|
| 76 |
+
if not token:
|
| 77 |
+
raise SystemExit("No HuggingFace token row in the CSV (use --token-csv).")
|
| 78 |
+
|
| 79 |
+
from huggingface_hub import HfApi # noqa: E402 (only needed for a real upload)
|
| 80 |
+
|
| 81 |
+
api = HfApi(token=token)
|
| 82 |
+
api.create_repo(a.repo, repo_type="dataset", private=False, exist_ok=True)
|
| 83 |
+
api.upload_large_folder(
|
| 84 |
+
repo_id=a.repo, repo_type="dataset", folder_path=out,
|
| 85 |
+
allow_patterns=["README.md", "data/**/*.parquet", "metadata/*.parquet", "pipeline/*"],
|
| 86 |
+
ignore_patterns=["**/*.tmp", "**/.DS_Store"],
|
| 87 |
+
)
|
| 88 |
+
print("done:", f"https://huggingface.co/datasets/{a.repo}")
|
pipeline/catalog_ftp_listing.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pipeline/codebook_pdf.R
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# codebook_pdf.R: parse NCHS NHIS codebook PDFs (via pdftotext -layout)
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Three NCHS documentation styles are handled:
|
| 5 |
+
# * "old" 1997-2003 codebooks (<file>.pdf): variable name, question
|
| 6 |
+
# text, question number/section, universe, universe description,
|
| 7 |
+
# location, label, published frequencies, sources, recodes,
|
| 8 |
+
# keywords, notes; the page header gives the record count.
|
| 9 |
+
# * "layout" 2004-2018 layout documents (<file>_layout.pdf): question ID,
|
| 10 |
+
# instrument variable name, question text, universe and its
|
| 11 |
+
# description, sources, recodes, keywords, notes (no counts).
|
| 12 |
+
# * "modern" 2019+ codebooks (<File>-codebook.pdf): module, section,
|
| 13 |
+
# question text, description, recode, universe, universe
|
| 14 |
+
# description, sources, question ID, keywords, notes and the
|
| 15 |
+
# unweighted frequency table.
|
| 16 |
+
# Each parser returns list(variables, values, records); unparsable pages are
|
| 17 |
+
# skipped (best effort, coverage is reported by 04_dictionary.R).
|
| 18 |
+
# Requires the poppler "pdftotext" command line tool.
|
| 19 |
+
# =============================================================================
|
| 20 |
+
|
| 21 |
+
# Text of a PDF with its layout preserved.
|
| 22 |
+
pdf_lines <- function(path) {
|
| 23 |
+
out <- tempfile(fileext = ".txt")
|
| 24 |
+
on.exit(unlink(out))
|
| 25 |
+
status <- system2("pdftotext", c("-layout", shQuote(path), shQuote(out)), stdout = FALSE, stderr = FALSE)
|
| 26 |
+
if (status != 0 || !file.exists(out)) {
|
| 27 |
+
return(character())
|
| 28 |
+
}
|
| 29 |
+
x <- readLines(out, warn = FALSE, encoding = "UTF-8")
|
| 30 |
+
x <- gsub("\f", "", x, fixed = TRUE)
|
| 31 |
+
x <- gsub(" ", " ", x)
|
| 32 |
+
sub("\\s+$", "", x)
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# Collapse whitespace and trim.
|
| 36 |
+
squish <- function(x) trimws(gsub("[[:space:]]+", " ", x))
|
| 37 |
+
|
| 38 |
+
# Empty variables / values frames.
|
| 39 |
+
empty_vars <- function() {
|
| 40 |
+
data.frame(
|
| 41 |
+
variable = character(), question_id = character(), question_text = character(),
|
| 42 |
+
universe = character(), universe_description = character(), sources = character(),
|
| 43 |
+
recodes = character(), keywords = character(), notes = character(),
|
| 44 |
+
module = character(), section = character(), doc_label = character(),
|
| 45 |
+
stringsAsFactors = FALSE
|
| 46 |
+
)
|
| 47 |
+
}
|
| 48 |
+
# Empty values frame (same columns as the parsers return).
|
| 49 |
+
empty_vals <- function() {
|
| 50 |
+
data.frame(
|
| 51 |
+
variable = character(), code = character(), description = character(),
|
| 52 |
+
count_published = numeric(), stringsAsFactors = FALSE
|
| 53 |
+
)
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
# Gather "Key: value" fields with indented continuation lines.
|
| 57 |
+
keyed_fields <- function(lines, keys) {
|
| 58 |
+
out <- setNames(as.list(rep(NA_character_, length(keys))), keys)
|
| 59 |
+
esc <- gsub(" ", "\\\\s+", gsub("([()])", "\\\\\\1", keys))
|
| 60 |
+
rx <- paste0("^\\s*(", paste(esc, collapse = "|"), "):\\s*(.*)$")
|
| 61 |
+
cur <- NA_character_
|
| 62 |
+
for (l in lines) {
|
| 63 |
+
if (grepl(rx, l, ignore.case = TRUE)) {
|
| 64 |
+
k <- sub(rx, "\\1", l, ignore.case = TRUE)
|
| 65 |
+
k <- keys[match(tolower(squish(k)), tolower(keys))]
|
| 66 |
+
out[[k]] <- squish(sub(rx, "\\2", l, ignore.case = TRUE))
|
| 67 |
+
cur <- k
|
| 68 |
+
} else if (!is.na(cur) && grepl("^\\s{4,}\\S", l)) {
|
| 69 |
+
out[[cur]] <- squish(paste(out[[cur]], l))
|
| 70 |
+
} else if (!is.na(cur) && !nzchar(squish(l))) {
|
| 71 |
+
next
|
| 72 |
+
} else {
|
| 73 |
+
cur <- NA_character_
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
lapply(out, function(v) if (!is.na(v) && !nzchar(v)) NA_character_ else v)
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
# ---- 2019+ codebooks ---------------------------------------------------------
|
| 80 |
+
|
| 81 |
+
# Parse a 2019+ "<File>-codebook.pdf".
|
| 82 |
+
parse_modern <- function(path) {
|
| 83 |
+
x <- pdf_lines(path)
|
| 84 |
+
hdr <- grepl("NATIONAL HEALTH INTERVIEW SURVEY \\(NHIS\\)|Codebook for .* file|^\\s*PUBLIC USE\\s*$|^\\s*Page [0-9]+\\s*$", x)
|
| 85 |
+
x <- x[!hdr]
|
| 86 |
+
start <- grep("^\\s*Variable:\\s+\\S", x)
|
| 87 |
+
vars <- list()
|
| 88 |
+
vals <- list()
|
| 89 |
+
keys <- c(
|
| 90 |
+
"Variable", "Module", "Section", "File(s)", "Data Type", "Length", "Question Text",
|
| 91 |
+
"Description", "Recode", "Universe", "Universe Description", "Sources", "Question ID",
|
| 92 |
+
"Keywords", "Notes", "Evaluation Report"
|
| 93 |
+
)
|
| 94 |
+
for (i in seq_along(start)) {
|
| 95 |
+
b <- x[start[i]:(if (i < length(start)) start[i + 1] - 1 else length(x))]
|
| 96 |
+
fq <- grep("^Unweighted frequencies:", b)
|
| 97 |
+
head <- if (length(fq)) b[seq_len(fq[1] - 1)] else b
|
| 98 |
+
f <- keyed_fields(head, keys)
|
| 99 |
+
v <- f[["Variable"]]
|
| 100 |
+
if (is.na(v)) next
|
| 101 |
+
v <- toupper(sub("\\s.*", "", v))
|
| 102 |
+
vars[[length(vars) + 1]] <- data.frame(
|
| 103 |
+
variable = v, question_id = f[["Question ID"]], question_text = f[["Question Text"]],
|
| 104 |
+
universe = f[["Universe"]], universe_description = f[["Universe Description"]],
|
| 105 |
+
sources = f[["Sources"]], recodes = f[["Recode"]], keywords = f[["Keywords"]],
|
| 106 |
+
notes = f[["Notes"]], module = f[["Module"]], section = f[["Section"]],
|
| 107 |
+
doc_label = f[["Description"]], stringsAsFactors = FALSE
|
| 108 |
+
)
|
| 109 |
+
if (length(fq)) {
|
| 110 |
+
tb <- b[(fq[1] + 1):length(b)]
|
| 111 |
+
tb <- tb[!grepl("^\\s*Code\\s+Description\\s+Frequency", tb)]
|
| 112 |
+
tb <- tb[!grepl(paste0("^", v, "\\s"), tb)]
|
| 113 |
+
rows <- list()
|
| 114 |
+
rx <- "^(\\S.*?)\\s{2,}(.*?)\\s+([0-9][0-9,]*)\\s+([0-9.]+)\\s*$"
|
| 115 |
+
for (l in tb) {
|
| 116 |
+
if (grepl("^Frequency Missing", l)) break
|
| 117 |
+
if (grepl(rx, l)) {
|
| 118 |
+
rows[[length(rows) + 1]] <- c(
|
| 119 |
+
squish(sub(rx, "\\1", l)), squish(sub(rx, "\\2", l)), sub(rx, "\\3", l)
|
| 120 |
+
)
|
| 121 |
+
} else if (length(rows) && nzchar(squish(l))) {
|
| 122 |
+
# Wrapped code ("1963-current" / "year") or description.
|
| 123 |
+
k <- length(rows)
|
| 124 |
+
lead <- !grepl("^\\s", l)
|
| 125 |
+
if (lead) {
|
| 126 |
+
rows[[k]][1] <- squish(paste(rows[[k]][1], sub("\\s{2,}.*", "", l)))
|
| 127 |
+
rest <- sub("^\\S+(\\s{2,})?", "", l)
|
| 128 |
+
if (nzchar(squish(rest))) rows[[k]][2] <- squish(paste(rows[[k]][2], rest))
|
| 129 |
+
} else {
|
| 130 |
+
rows[[k]][2] <- squish(paste(rows[[k]][2], l))
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
if (length(rows)) {
|
| 135 |
+
m <- do.call(rbind, rows)
|
| 136 |
+
vals[[length(vals) + 1]] <- data.frame(
|
| 137 |
+
variable = v, code = m[, 1], description = m[, 2],
|
| 138 |
+
count_published = as.numeric(gsub(",", "", m[, 3])), stringsAsFactors = FALSE
|
| 139 |
+
)
|
| 140 |
+
}
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
list(
|
| 144 |
+
variables = if (length(vars)) do.call(rbind, vars) else empty_vars(),
|
| 145 |
+
values = if (length(vals)) do.call(rbind, vals) else empty_vals(),
|
| 146 |
+
records = NA_real_
|
| 147 |
+
)
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
# ---- 2004-2018 layout documents ------------------------------------------------
|
| 151 |
+
|
| 152 |
+
# Parse a 2004-2018 "<file>_layout.pdf".
|
| 153 |
+
parse_layout <- function(path) {
|
| 154 |
+
x <- pdf_lines(path)
|
| 155 |
+
# Drop page headers: from "Page n of m" through "Document Version Date".
|
| 156 |
+
pg <- grep("^\\s*Page [0-9]+ of [0-9]+\\s*$", x)
|
| 157 |
+
drop <- logical(length(x))
|
| 158 |
+
for (p in pg) {
|
| 159 |
+
e <- grep("Document Version Date", x[p:min(length(x), p + 12)])
|
| 160 |
+
if (length(e)) drop[p:(p + e[1] - 1)] <- TRUE else drop[p] <- TRUE
|
| 161 |
+
}
|
| 162 |
+
x <- x[!drop]
|
| 163 |
+
start <- grep("^\\s*Question ID:", x)
|
| 164 |
+
vars <- list()
|
| 165 |
+
for (i in seq_along(start)) {
|
| 166 |
+
b <- x[start[i]:(if (i < length(start)) start[i + 1] - 1 else length(x))]
|
| 167 |
+
qid <- squish(sub(".*Question ID:\\s*(\\S+).*", "\\1", b[1]))
|
| 168 |
+
if (grepl("Instrument Variable Name", qid)) qid <- NA_character_
|
| 169 |
+
inst <- squish(sub(".*Instrument Variable Name:\\s*", "", b[1]))
|
| 170 |
+
if (!grepl("Instrument Variable Name", b[1])) inst <- NA_character_
|
| 171 |
+
# "Final Documentation Name:" (2005+) or without the colon (2004).
|
| 172 |
+
fdn <- grep("Final Documentation Name", b)
|
| 173 |
+
if (!length(fdn)) next
|
| 174 |
+
v <- toupper(squish(sub(".*Final Documentation Name:?\\s*", "", b[fdn[1]])))
|
| 175 |
+
v <- sub("\\s.*", "", v)
|
| 176 |
+
uni <- grep("^\\s*Universe:", b)
|
| 177 |
+
qtext <- if (length(uni) && uni[1] > fdn[1] + 1) squish(paste(b[(fdn[1] + 1):(uni[1] - 1)], collapse = " ")) else NA_character_
|
| 178 |
+
notes_end <- length(b)
|
| 179 |
+
f <- keyed_fields(b[(if (length(uni)) uni[1] else fdn[1]):notes_end],
|
| 180 |
+
c("Universe", "Description", "Sources", "Recodes", "Keywords", "Notes")
|
| 181 |
+
)
|
| 182 |
+
# Empty or "None" fields become NA.
|
| 183 |
+
nz <- function(z) if (is.na(z) || !nzchar(z) || z == "None") NA_character_ else z
|
| 184 |
+
vars[[length(vars) + 1]] <- data.frame(
|
| 185 |
+
variable = v, question_id = paste0(qid, ifelse(is.na(inst) || !nzchar(inst), "", paste0(" (", inst, ")"))),
|
| 186 |
+
question_text = nz(qtext), universe = nz(f$Universe),
|
| 187 |
+
universe_description = nz(f$Description), sources = nz(f$Sources),
|
| 188 |
+
recodes = nz(f$Recodes), keywords = nz(f$Keywords), notes = nz(f$Notes),
|
| 189 |
+
module = NA_character_, section = NA_character_, doc_label = NA_character_,
|
| 190 |
+
stringsAsFactors = FALSE
|
| 191 |
+
)
|
| 192 |
+
}
|
| 193 |
+
list(
|
| 194 |
+
variables = if (length(vars)) do.call(rbind, vars) else empty_vars(),
|
| 195 |
+
values = empty_vals(), records = NA_real_
|
| 196 |
+
)
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
# ---- 1997-2003 codebooks -------------------------------------------------------
|
| 200 |
+
|
| 201 |
+
# Parse a 1997-2003 "<file>.pdf" codebook.
|
| 202 |
+
parse_old <- function(path) {
|
| 203 |
+
x <- pdf_lines(path)
|
| 204 |
+
rec <- regmatches(x, regexpr("[0-9][0-9,]* RECORDS", x))
|
| 205 |
+
records <- if (length(rec)) as.numeric(gsub("[^0-9]", "", rec[1])) else NA_real_
|
| 206 |
+
sep <- grep("^\\s*_{20,}\\s*$", x)
|
| 207 |
+
vars <- list()
|
| 208 |
+
vals <- list()
|
| 209 |
+
for (i in seq_along(sep)) {
|
| 210 |
+
b <- x[(sep[i] + 1):(if (i < length(sep)) sep[i + 1] - 1 else length(x))]
|
| 211 |
+
if (!length(b) || !grepl("^[A-Z][A-Z0-9_]+(\\s|$)", b[1])) next
|
| 212 |
+
if (grepl("^Variable Name\\s", b[1])) next
|
| 213 |
+
if (any(grepl("NATIONAL HEALTH INTERVIEW SURVEY", b))) next
|
| 214 |
+
v <- sub("\\s.*", "", b[1])
|
| 215 |
+
qtext <- squish(substring(b[1], nchar(v) + 1))
|
| 216 |
+
j <- 2
|
| 217 |
+
# Question text continues on indented lines until the question number line.
|
| 218 |
+
while (j <= length(b) && grepl("^\\s{10,}\\S", b[j]) && !grepl("^\\s*[0-9]+(-\\s*[0-9]+)?\\s{2,}", b[j])) {
|
| 219 |
+
qtext <- squish(paste(qtext, b[j]))
|
| 220 |
+
j <- j + 1
|
| 221 |
+
}
|
| 222 |
+
qno <- NA_character_
|
| 223 |
+
if (j <= length(b) && grepl("^\\S", b[j])) {
|
| 224 |
+
qno <- squish(substr(b[j], 1, 26))
|
| 225 |
+
more <- squish(substring(b[j], 27))
|
| 226 |
+
if (nzchar(more)) qtext <- squish(paste(qtext, more))
|
| 227 |
+
j <- j + 1
|
| 228 |
+
}
|
| 229 |
+
# Universe and universe description: next two groups of indented lines.
|
| 230 |
+
groups <- list()
|
| 231 |
+
cur <- character()
|
| 232 |
+
loc <- NA
|
| 233 |
+
while (j <= length(b)) {
|
| 234 |
+
l <- b[j]
|
| 235 |
+
if (grepl("^\\s{0,4}[0-9]+(\\s*-\\s*[0-9]+)?\\s{3,}\\S", l)) {
|
| 236 |
+
loc <- j
|
| 237 |
+
break
|
| 238 |
+
}
|
| 239 |
+
if (!nzchar(squish(l))) {
|
| 240 |
+
if (length(cur)) groups[[length(groups) + 1]] <- squish(paste(cur, collapse = " "))
|
| 241 |
+
cur <- character()
|
| 242 |
+
} else {
|
| 243 |
+
cur <- c(cur, l)
|
| 244 |
+
}
|
| 245 |
+
j <- j + 1
|
| 246 |
+
}
|
| 247 |
+
if (length(cur)) groups[[length(groups) + 1]] <- squish(paste(cur, collapse = " "))
|
| 248 |
+
if (is.na(loc)) next
|
| 249 |
+
label <- squish(sub("^\\s*[0-9]+(\\s*-\\s*[0-9]+)?\\s+", "", b[loc]))
|
| 250 |
+
tail_b <- b[(loc + 1):length(b)]
|
| 251 |
+
src <- grep("^Sources:", tail_b)
|
| 252 |
+
val_lines <- if (length(src)) tail_b[seq_len(src[1] - 1)] else tail_b
|
| 253 |
+
f <- keyed_fields(if (length(src)) tail_b[src[1]:length(tail_b)] else character(),
|
| 254 |
+
c("Sources", "Recodes", "Keywords", "Notes")
|
| 255 |
+
)
|
| 256 |
+
# Empty or "None" fields become NA.
|
| 257 |
+
nz <- function(z) if (is.null(z) || is.na(z) || !nzchar(z) || z == "None") NA_character_ else z
|
| 258 |
+
vars[[length(vars) + 1]] <- data.frame(
|
| 259 |
+
variable = toupper(v), question_id = qno,
|
| 260 |
+
question_text = nz(if (qtext %in% c("Generated variable", "Recode")) NA_character_ else qtext),
|
| 261 |
+
universe = nz(if (length(groups) >= 1) groups[[1]] else NA_character_),
|
| 262 |
+
universe_description = nz(if (length(groups) >= 2) paste(unlist(groups[-1]), collapse = " ") else NA_character_),
|
| 263 |
+
sources = nz(f$Sources), recodes = nz(f$Recodes), keywords = nz(f$Keywords),
|
| 264 |
+
notes = nz(f$Notes), module = NA_character_, section = NA_character_,
|
| 265 |
+
doc_label = label, stringsAsFactors = FALSE
|
| 266 |
+
)
|
| 267 |
+
rows <- list()
|
| 268 |
+
rx <- "^\\s*([0-9][0-9,]*)\\s{2,}(\\S+)\\s+(.*)$"
|
| 269 |
+
rxb <- "^\\s*([0-9][0-9,]*)\\s{2,}(<.*)$"
|
| 270 |
+
for (l in val_lines) {
|
| 271 |
+
if (grepl(rxb, l)) {
|
| 272 |
+
rows[[length(rows) + 1]] <- c("", squish(sub(rxb, "\\2", l)), sub(rxb, "\\1", l))
|
| 273 |
+
} else if (grepl(rx, l)) {
|
| 274 |
+
rows[[length(rows) + 1]] <- c(sub(rx, "\\2", l), squish(sub(rx, "\\3", l)), sub(rx, "\\1", l))
|
| 275 |
+
} else if (length(rows) && grepl("^\\s{20,}\\S", l)) {
|
| 276 |
+
k <- length(rows)
|
| 277 |
+
rows[[k]][2] <- squish(paste(rows[[k]][2], l))
|
| 278 |
+
}
|
| 279 |
+
}
|
| 280 |
+
if (length(rows)) {
|
| 281 |
+
m <- do.call(rbind, rows)
|
| 282 |
+
vals[[length(vals) + 1]] <- data.frame(
|
| 283 |
+
variable = toupper(v), code = m[, 1], description = m[, 2],
|
| 284 |
+
count_published = as.numeric(gsub(",", "", m[, 3])), stringsAsFactors = FALSE
|
| 285 |
+
)
|
| 286 |
+
}
|
| 287 |
+
}
|
| 288 |
+
list(
|
| 289 |
+
variables = if (length(vars)) do.call(rbind, vars) else empty_vars(),
|
| 290 |
+
values = if (length(vals)) do.call(rbind, vals) else empty_vals(),
|
| 291 |
+
records = records
|
| 292 |
+
)
|
| 293 |
+
}
|
pipeline/files_spec.R
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# files_spec.R: one row per NHIS data file to convert, with its NCHS program
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Builds the conversion inventory from ../catalog_ftp_listing.csv and the
|
| 5 |
+
# contents of the downloaded archives:
|
| 6 |
+
# year, component, file (output name = upper-cased NCHS data file name),
|
| 7 |
+
# stem (file type), archive (raw path), member (file inside the ZIP or NA),
|
| 8 |
+
# reader (fwf / sas7bdat / revwts_csv / mortality), program (SAS input
|
| 9 |
+
# program used for the layout), section (part of the program to parse),
|
| 10 |
+
# layout_note (where the layout came from), source_url, doc_url.
|
| 11 |
+
# Choices (documented in the dataset card):
|
| 12 |
+
# * 1997-2025 ASCII (.dat) files are read with the NCHS SAS INPUT layout;
|
| 13 |
+
# the CSV copies NCHS also publishes (2015-2025) are kept in raw/ only and
|
| 14 |
+
# used to cross-check values (05_validate.R).
|
| 15 |
+
# * Pair weights (2019+) are read from the NCHS SAS data set (.sas7bdat).
|
| 16 |
+
# * 2016 revised weights exist only as CSV (with an NCHS SAS import note).
|
| 17 |
+
# * Linked mortality uses the NHIS section of the NCHS read-in program.
|
| 18 |
+
# =============================================================================
|
| 19 |
+
|
| 20 |
+
# Component (folder) of a file type stem.
|
| 21 |
+
component_of <- function(stem) {
|
| 22 |
+
s <- toupper(stem)
|
| 23 |
+
if (s %in% c("HOUSEHLD", "FAMILYXX", "PERSONSX", "SAMADULT", "SAMCHILD", "ADULT", "CHILD")) {
|
| 24 |
+
return("Core")
|
| 25 |
+
}
|
| 26 |
+
if (s %in% c("ADULTLONG", "ADULTPART")) {
|
| 27 |
+
return("Longitudinal")
|
| 28 |
+
}
|
| 29 |
+
if (s %in% c("INJEPSOD", "POIEPSOD", "INJPOIEP", "INJVERBT")) {
|
| 30 |
+
return("Injury")
|
| 31 |
+
}
|
| 32 |
+
if (s %in% c("INCMIMP", "INCIMPS", "ADULTINC", "CHILDINC")) {
|
| 33 |
+
return("ImputedIncome")
|
| 34 |
+
}
|
| 35 |
+
if (s == "PARADATA") {
|
| 36 |
+
return("Paradata")
|
| 37 |
+
}
|
| 38 |
+
if (s %in% c("FINAL_PAIR_WEIGHT", "REVWTS", "SAD_WGTS", "SINGLETON")) {
|
| 39 |
+
return("Design")
|
| 40 |
+
}
|
| 41 |
+
"Supplement"
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
# Type stem of a data member name: drop year suffixes, implicate numbers,
|
| 45 |
+
# "2003" style prefixes of the singleton files.
|
| 46 |
+
stem_of <- function(member, year) {
|
| 47 |
+
s <- toupper(tools::file_path_sans_ext(basename(member)))
|
| 48 |
+
if (grepl("^SC_BWT", s)) {
|
| 49 |
+
return("SC_BWT")
|
| 50 |
+
}
|
| 51 |
+
if (grepl("REVWTS", s)) {
|
| 52 |
+
return("REVWTS")
|
| 53 |
+
}
|
| 54 |
+
if (grepl("^FINAL_PAIR_WEIGHT", s)) {
|
| 55 |
+
return("FINAL_PAIR_WEIGHT")
|
| 56 |
+
}
|
| 57 |
+
if (grepl("^INCMAP[1-5]$", s)) {
|
| 58 |
+
return("INCMIMP")
|
| 59 |
+
}
|
| 60 |
+
s <- sub("^(INCMIMP|INCIMPS)[1-5]$", "\\1", s)
|
| 61 |
+
s <- sub(paste0("^", year), "", s)
|
| 62 |
+
if (year >= 2019) s <- sub(sprintf("%02d$", year %% 100), "", s)
|
| 63 |
+
if (s == "RATCAT07") s <- "RATCAT"
|
| 64 |
+
s
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
# Build the inventory (lists ZIP members with bsdtar/unzip, never extracts).
|
| 68 |
+
build_spec <- function() {
|
| 69 |
+
x <- read_catalog()
|
| 70 |
+
progs <- x[grepl("\\.sas$", x$file, ignore.case = TRUE), ]
|
| 71 |
+
# Codebooks: documentation folders (2004 keeps them beside the programs).
|
| 72 |
+
docs <- x[x$kind %in% c("documentation", "program") & grepl("\\.pdf$", x$file, ignore.case = TRUE), ]
|
| 73 |
+
d <- x[x$kind %in% c("data", "imputed_income", "paradata") &
|
| 74 |
+
grepl("\\.(zip|dat)$", x$file, ignore.case = TRUE), ]
|
| 75 |
+
# 1997-2018: ASCII is the source; CSV copies (2015-2018) are kept raw only
|
| 76 |
+
# and used for the cross-check. 2019+: the CSV is the source because the
|
| 77 |
+
# ASCII fields round the weights to the field width (e.g. WTFA_A
|
| 78 |
+
# 13177.008 in CSV is 13177.01 in ASCII); the pair-weight SAS data set is
|
| 79 |
+
# used instead of its CSV copy.
|
| 80 |
+
is_csv <- grepl("csv\\.zip$", d$file, ignore.case = TRUE)
|
| 81 |
+
pair <- grepl("pair", d$file, ignore.case = TRUE)
|
| 82 |
+
keep <- ifelse(d$year >= 2019, (is_csv & !pair) | (!is_csv & pair), !is_csv | grepl("revwts", d$file))
|
| 83 |
+
d <- d[keep & !grepl("RevWts-SAS\\.zip$", d$file), ]
|
| 84 |
+
rows <- list()
|
| 85 |
+
for (i in seq_len(nrow(d))) {
|
| 86 |
+
r <- d[i, ]
|
| 87 |
+
members <- if (grepl("\\.zip$", r$file, ignore.case = TRUE)) {
|
| 88 |
+
m <- utils::unzip(r$raw, list = TRUE)$Name
|
| 89 |
+
m[!grepl("readme", m, ignore.case = TRUE) &
|
| 90 |
+
(!grepl("\\.csv$", m, ignore.case = TRUE) | grepl("revwts", m) | r$year >= 2019)]
|
| 91 |
+
} else {
|
| 92 |
+
NA_character_
|
| 93 |
+
}
|
| 94 |
+
for (m in members) {
|
| 95 |
+
nm <- if (is.na(m)) r$file else m
|
| 96 |
+
if (grepl("\\.csv$", nm, ignore.case = TRUE) && !grepl("revwts", nm) && r$year < 2019) next
|
| 97 |
+
stem <- stem_of(nm, r$year)
|
| 98 |
+
single <- grepl("/singleton/", r$folder)
|
| 99 |
+
rows[[length(rows) + 1]] <- data.frame(
|
| 100 |
+
year = r$year, stem = stem,
|
| 101 |
+
component = if (single) "Design" else component_of(stem),
|
| 102 |
+
file = toupper(tools::file_path_sans_ext(basename(nm))),
|
| 103 |
+
archive = r$raw, member = m, source_url = r$url,
|
| 104 |
+
singleton = single, stringsAsFactors = FALSE
|
| 105 |
+
)
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
s <- do.call(rbind, rows)
|
| 109 |
+
s$file <- gsub("-", "_", s$file)
|
| 110 |
+
# Reader and program for each file.
|
| 111 |
+
s$reader <- "fwf"
|
| 112 |
+
s$program <- NA_character_
|
| 113 |
+
s$section <- NA_character_
|
| 114 |
+
s$layout_note <- "NCHS SAS input program"
|
| 115 |
+
# First SAS program of the year whose name matches the pattern.
|
| 116 |
+
find_prog <- function(year, pattern) {
|
| 117 |
+
p <- progs[progs$year == year & grepl(pattern, progs$file, ignore.case = TRUE), ]
|
| 118 |
+
if (nrow(p)) p$raw[1] else NA_character_
|
| 119 |
+
}
|
| 120 |
+
for (i in seq_len(nrow(s))) {
|
| 121 |
+
y <- s$year[i]
|
| 122 |
+
st <- s$stem[i]
|
| 123 |
+
if (st == "FINAL_PAIR_WEIGHT") {
|
| 124 |
+
s$reader[i] <- "sas7bdat"
|
| 125 |
+
s$layout_note[i] <- "NCHS SAS data set (labels from the file)"
|
| 126 |
+
next
|
| 127 |
+
}
|
| 128 |
+
if (st == "REVWTS") {
|
| 129 |
+
s$reader[i] <- "revwts_csv"
|
| 130 |
+
s$layout_note[i] <- "NCHS CSV with SAS import program (RevWts-SAS.zip)"
|
| 131 |
+
next
|
| 132 |
+
}
|
| 133 |
+
if (st == "SAD_WGTS") {
|
| 134 |
+
s$program[i] <- find_prog(y, "^sam_disb\\.sas$")
|
| 135 |
+
s$section[i] <- "sad_wgts"
|
| 136 |
+
s$layout_note[i] <- "INPUT statement for SAD_WGTS in the NCHS program sam_disb.sas"
|
| 137 |
+
next
|
| 138 |
+
}
|
| 139 |
+
if (st == "SC_BWT") {
|
| 140 |
+
s$program[i] <- find_prog(y, paste0("^", s$file[i], "\\.sas$"))
|
| 141 |
+
next
|
| 142 |
+
}
|
| 143 |
+
if (st == "RATCAT") {
|
| 144 |
+
s$program[i] <- find_prog(y, "^ratcat07\\.sas$")
|
| 145 |
+
next
|
| 146 |
+
}
|
| 147 |
+
if (st == "INCMIMP" && y <= 2004) {
|
| 148 |
+
# No SAS program on the FTP for 1997-2004; the record layout is the
|
| 149 |
+
# one documented in datdocYY.pdf, identical to the 2005 program
|
| 150 |
+
# (person number is named PX through 2003).
|
| 151 |
+
s$program[i] <- x$raw[x$year == 2005 & x$file == "INCMIMP.sas"][1]
|
| 152 |
+
s$section[i] <- if (y <= 2003) "incmimp_px" else NA_character_
|
| 153 |
+
s$layout_note[i] <- sprintf(
|
| 154 |
+
"2005 NCHS INCMIMP.sas layout; identical to the %d dataset documentation datdoc%02d.pdf",
|
| 155 |
+
y, y %% 100
|
| 156 |
+
)
|
| 157 |
+
next
|
| 158 |
+
}
|
| 159 |
+
if (y >= 2019) {
|
| 160 |
+
s$reader[i] <- "csv"
|
| 161 |
+
s$layout_note[i] <- "NCHS CSV; variable order and types from the NCHS SAS input program"
|
| 162 |
+
}
|
| 163 |
+
p <- find_prog(y, paste0("^", st, "\\.sas$"))
|
| 164 |
+
if (is.na(p) && st == "SC_BWT") p <- find_prog(y, "^SC_BWT")
|
| 165 |
+
s$program[i] <- p
|
| 166 |
+
}
|
| 167 |
+
mort <- x[x$kind == "mortality" & grepl("^NHIS_.*\\.dat$", x$file), ]
|
| 168 |
+
mort_prog <- x$raw[x$kind == "mortality" & x$file == "SAS_ReadInProgramAllSurveys.sas"][1]
|
| 169 |
+
if (nrow(mort)) {
|
| 170 |
+
s <- rbind(s, data.frame(
|
| 171 |
+
year = mort$year, stem = "MORT", component = "Mortality",
|
| 172 |
+
file = toupper(tools::file_path_sans_ext(mort$file)), archive = mort$raw,
|
| 173 |
+
member = NA_character_, source_url = mort$url, singleton = FALSE,
|
| 174 |
+
reader = "fwf", program = mort_prog, section = "mortality",
|
| 175 |
+
layout_note = "NHIS section of the NCHS linked mortality SAS read-in program",
|
| 176 |
+
stringsAsFactors = FALSE
|
| 177 |
+
))
|
| 178 |
+
}
|
| 179 |
+
# Documentation (codebook) used by 04_dictionary.R.
|
| 180 |
+
s$doc <- NA_character_
|
| 181 |
+
for (i in seq_len(nrow(s))) {
|
| 182 |
+
dd <- docs[docs$year == s$year[i], ]
|
| 183 |
+
st <- tolower(s$stem[i])
|
| 184 |
+
# First documentation PDF of the year whose name matches rx.
|
| 185 |
+
pick <- function(rx) {
|
| 186 |
+
k <- grep(rx, dd$file, ignore.case = TRUE)
|
| 187 |
+
if (length(k)) dd$raw[k[1]] else NA_character_
|
| 188 |
+
}
|
| 189 |
+
if (s$stem[i] == "MORT" || s$reader[i] %in% c("sas7bdat", "revwts_csv")) next
|
| 190 |
+
s$doc[i] <- if (s$year[i] >= 2019) {
|
| 191 |
+
pick(paste0("^", st, "-codebook\\.pdf$"))
|
| 192 |
+
} else if (s$year[i] <= 2003) {
|
| 193 |
+
pick(paste0("^", st, "\\.pdf$"))
|
| 194 |
+
} else {
|
| 195 |
+
pick(paste0("^", st, "_layout\\.pdf$"))
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
s$path <- file.path("data", s$year, s$component, paste0(s$file, ".parquet"))
|
| 199 |
+
s <- s[order(s$year, s$component, s$file), ]
|
| 200 |
+
rownames(s) <- NULL
|
| 201 |
+
s
|
| 202 |
+
}
|
pipeline/hf_configs.yaml
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
configs:
|
| 2 |
+
- config_name: files
|
| 3 |
+
data_files:
|
| 4 |
+
- split: all
|
| 5 |
+
path: metadata/FILES.parquet
|
| 6 |
+
- config_name: years
|
| 7 |
+
data_files:
|
| 8 |
+
- split: all
|
| 9 |
+
path: metadata/YEARS.parquet
|
| 10 |
+
- config_name: dictionary_variables
|
| 11 |
+
data_files:
|
| 12 |
+
- split: year_1997
|
| 13 |
+
path: data/1997/Dictionary/VARIABLES.parquet
|
| 14 |
+
- split: year_1998
|
| 15 |
+
path: data/1998/Dictionary/VARIABLES.parquet
|
| 16 |
+
- split: year_1999
|
| 17 |
+
path: data/1999/Dictionary/VARIABLES.parquet
|
| 18 |
+
- split: year_2000
|
| 19 |
+
path: data/2000/Dictionary/VARIABLES.parquet
|
| 20 |
+
- split: year_2001
|
| 21 |
+
path: data/2001/Dictionary/VARIABLES.parquet
|
| 22 |
+
- split: year_2002
|
| 23 |
+
path: data/2002/Dictionary/VARIABLES.parquet
|
| 24 |
+
- split: year_2003
|
| 25 |
+
path: data/2003/Dictionary/VARIABLES.parquet
|
| 26 |
+
- split: year_2004
|
| 27 |
+
path: data/2004/Dictionary/VARIABLES.parquet
|
| 28 |
+
- split: year_2005
|
| 29 |
+
path: data/2005/Dictionary/VARIABLES.parquet
|
| 30 |
+
- split: year_2006
|
| 31 |
+
path: data/2006/Dictionary/VARIABLES.parquet
|
| 32 |
+
- split: year_2007
|
| 33 |
+
path: data/2007/Dictionary/VARIABLES.parquet
|
| 34 |
+
- split: year_2008
|
| 35 |
+
path: data/2008/Dictionary/VARIABLES.parquet
|
| 36 |
+
- split: year_2009
|
| 37 |
+
path: data/2009/Dictionary/VARIABLES.parquet
|
| 38 |
+
- split: year_2010
|
| 39 |
+
path: data/2010/Dictionary/VARIABLES.parquet
|
| 40 |
+
- split: year_2011
|
| 41 |
+
path: data/2011/Dictionary/VARIABLES.parquet
|
| 42 |
+
- split: year_2012
|
| 43 |
+
path: data/2012/Dictionary/VARIABLES.parquet
|
| 44 |
+
- split: year_2013
|
| 45 |
+
path: data/2013/Dictionary/VARIABLES.parquet
|
| 46 |
+
- split: year_2014
|
| 47 |
+
path: data/2014/Dictionary/VARIABLES.parquet
|
| 48 |
+
- split: year_2015
|
| 49 |
+
path: data/2015/Dictionary/VARIABLES.parquet
|
| 50 |
+
- split: year_2016
|
| 51 |
+
path: data/2016/Dictionary/VARIABLES.parquet
|
| 52 |
+
- split: year_2017
|
| 53 |
+
path: data/2017/Dictionary/VARIABLES.parquet
|
| 54 |
+
- split: year_2018
|
| 55 |
+
path: data/2018/Dictionary/VARIABLES.parquet
|
| 56 |
+
- split: year_2019
|
| 57 |
+
path: data/2019/Dictionary/VARIABLES.parquet
|
| 58 |
+
- split: year_2020
|
| 59 |
+
path: data/2020/Dictionary/VARIABLES.parquet
|
| 60 |
+
- split: year_2021
|
| 61 |
+
path: data/2021/Dictionary/VARIABLES.parquet
|
| 62 |
+
- split: year_2022
|
| 63 |
+
path: data/2022/Dictionary/VARIABLES.parquet
|
| 64 |
+
- split: year_2023
|
| 65 |
+
path: data/2023/Dictionary/VARIABLES.parquet
|
| 66 |
+
- split: year_2024
|
| 67 |
+
path: data/2024/Dictionary/VARIABLES.parquet
|
| 68 |
+
- split: year_2025
|
| 69 |
+
path: data/2025/Dictionary/VARIABLES.parquet
|
| 70 |
+
- config_name: dictionary_values
|
| 71 |
+
data_files:
|
| 72 |
+
- split: year_1997
|
| 73 |
+
path: data/1997/Dictionary/VALUES.parquet
|
| 74 |
+
- split: year_1998
|
| 75 |
+
path: data/1998/Dictionary/VALUES.parquet
|
| 76 |
+
- split: year_1999
|
| 77 |
+
path: data/1999/Dictionary/VALUES.parquet
|
| 78 |
+
- split: year_2000
|
| 79 |
+
path: data/2000/Dictionary/VALUES.parquet
|
| 80 |
+
- split: year_2001
|
| 81 |
+
path: data/2001/Dictionary/VALUES.parquet
|
| 82 |
+
- split: year_2002
|
| 83 |
+
path: data/2002/Dictionary/VALUES.parquet
|
| 84 |
+
- split: year_2003
|
| 85 |
+
path: data/2003/Dictionary/VALUES.parquet
|
| 86 |
+
- split: year_2004
|
| 87 |
+
path: data/2004/Dictionary/VALUES.parquet
|
| 88 |
+
- split: year_2005
|
| 89 |
+
path: data/2005/Dictionary/VALUES.parquet
|
| 90 |
+
- split: year_2006
|
| 91 |
+
path: data/2006/Dictionary/VALUES.parquet
|
| 92 |
+
- split: year_2007
|
| 93 |
+
path: data/2007/Dictionary/VALUES.parquet
|
| 94 |
+
- split: year_2008
|
| 95 |
+
path: data/2008/Dictionary/VALUES.parquet
|
| 96 |
+
- split: year_2009
|
| 97 |
+
path: data/2009/Dictionary/VALUES.parquet
|
| 98 |
+
- split: year_2010
|
| 99 |
+
path: data/2010/Dictionary/VALUES.parquet
|
| 100 |
+
- split: year_2011
|
| 101 |
+
path: data/2011/Dictionary/VALUES.parquet
|
| 102 |
+
- split: year_2012
|
| 103 |
+
path: data/2012/Dictionary/VALUES.parquet
|
| 104 |
+
- split: year_2013
|
| 105 |
+
path: data/2013/Dictionary/VALUES.parquet
|
| 106 |
+
- split: year_2014
|
| 107 |
+
path: data/2014/Dictionary/VALUES.parquet
|
| 108 |
+
- split: year_2015
|
| 109 |
+
path: data/2015/Dictionary/VALUES.parquet
|
| 110 |
+
- split: year_2016
|
| 111 |
+
path: data/2016/Dictionary/VALUES.parquet
|
| 112 |
+
- split: year_2017
|
| 113 |
+
path: data/2017/Dictionary/VALUES.parquet
|
| 114 |
+
- split: year_2018
|
| 115 |
+
path: data/2018/Dictionary/VALUES.parquet
|
| 116 |
+
- split: year_2019
|
| 117 |
+
path: data/2019/Dictionary/VALUES.parquet
|
| 118 |
+
- split: year_2020
|
| 119 |
+
path: data/2020/Dictionary/VALUES.parquet
|
| 120 |
+
- split: year_2021
|
| 121 |
+
path: data/2021/Dictionary/VALUES.parquet
|
| 122 |
+
- split: year_2022
|
| 123 |
+
path: data/2022/Dictionary/VALUES.parquet
|
| 124 |
+
- split: year_2023
|
| 125 |
+
path: data/2023/Dictionary/VALUES.parquet
|
| 126 |
+
- split: year_2024
|
| 127 |
+
path: data/2024/Dictionary/VALUES.parquet
|
| 128 |
+
- split: year_2025
|
| 129 |
+
path: data/2025/Dictionary/VALUES.parquet
|
| 130 |
+
- config_name: linked_mortality
|
| 131 |
+
data_files:
|
| 132 |
+
- split: year_1997
|
| 133 |
+
path: data/1997/Mortality/NHIS_1997_MORT_2019_PUBLIC.parquet
|
| 134 |
+
- split: year_1998
|
| 135 |
+
path: data/1998/Mortality/NHIS_1998_MORT_2019_PUBLIC.parquet
|
| 136 |
+
- split: year_1999
|
| 137 |
+
path: data/1999/Mortality/NHIS_1999_MORT_2019_PUBLIC.parquet
|
| 138 |
+
- split: year_2000
|
| 139 |
+
path: data/2000/Mortality/NHIS_2000_MORT_2019_PUBLIC.parquet
|
| 140 |
+
- split: year_2001
|
| 141 |
+
path: data/2001/Mortality/NHIS_2001_MORT_2019_PUBLIC.parquet
|
| 142 |
+
- split: year_2002
|
| 143 |
+
path: data/2002/Mortality/NHIS_2002_MORT_2019_PUBLIC.parquet
|
| 144 |
+
- split: year_2003
|
| 145 |
+
path: data/2003/Mortality/NHIS_2003_MORT_2019_PUBLIC.parquet
|
| 146 |
+
- split: year_2004
|
| 147 |
+
path: data/2004/Mortality/NHIS_2004_MORT_2019_PUBLIC.parquet
|
| 148 |
+
- split: year_2005
|
| 149 |
+
path: data/2005/Mortality/NHIS_2005_MORT_2019_PUBLIC.parquet
|
| 150 |
+
- split: year_2006
|
| 151 |
+
path: data/2006/Mortality/NHIS_2006_MORT_2019_PUBLIC.parquet
|
| 152 |
+
- split: year_2007
|
| 153 |
+
path: data/2007/Mortality/NHIS_2007_MORT_2019_PUBLIC.parquet
|
| 154 |
+
- split: year_2008
|
| 155 |
+
path: data/2008/Mortality/NHIS_2008_MORT_2019_PUBLIC.parquet
|
| 156 |
+
- split: year_2009
|
| 157 |
+
path: data/2009/Mortality/NHIS_2009_MORT_2019_PUBLIC.parquet
|
| 158 |
+
- split: year_2010
|
| 159 |
+
path: data/2010/Mortality/NHIS_2010_MORT_2019_PUBLIC.parquet
|
| 160 |
+
- split: year_2011
|
| 161 |
+
path: data/2011/Mortality/NHIS_2011_MORT_2019_PUBLIC.parquet
|
| 162 |
+
- split: year_2012
|
| 163 |
+
path: data/2012/Mortality/NHIS_2012_MORT_2019_PUBLIC.parquet
|
| 164 |
+
- split: year_2013
|
| 165 |
+
path: data/2013/Mortality/NHIS_2013_MORT_2019_PUBLIC.parquet
|
| 166 |
+
- split: year_2014
|
| 167 |
+
path: data/2014/Mortality/NHIS_2014_MORT_2019_PUBLIC.parquet
|
| 168 |
+
- split: year_2015
|
| 169 |
+
path: data/2015/Mortality/NHIS_2015_MORT_2019_PUBLIC.parquet
|
| 170 |
+
- split: year_2016
|
| 171 |
+
path: data/2016/Mortality/NHIS_2016_MORT_2019_PUBLIC.parquet
|
| 172 |
+
- split: year_2017
|
| 173 |
+
path: data/2017/Mortality/NHIS_2017_MORT_2019_PUBLIC.parquet
|
| 174 |
+
- split: year_2018
|
| 175 |
+
path: data/2018/Mortality/NHIS_2018_MORT_2019_PUBLIC.parquet
|
| 176 |
+
- config_name: pair_weights
|
| 177 |
+
data_files:
|
| 178 |
+
- split: year_2019
|
| 179 |
+
path: data/2019/Design/FINAL_PAIR_WEIGHT2019.parquet
|
| 180 |
+
- split: year_2020
|
| 181 |
+
path: data/2020/Design/FINAL_PAIR_WEIGHT2020.parquet
|
| 182 |
+
- split: year_2021
|
| 183 |
+
path: data/2021/Design/FINAL_PAIR_WEIGHT2021.parquet
|
| 184 |
+
- split: year_2022
|
| 185 |
+
path: data/2022/Design/FINAL_PAIR_WEIGHT2022.parquet
|
| 186 |
+
- split: year_2023
|
| 187 |
+
path: data/2023/Design/FINAL_PAIR_WEIGHT2023.parquet
|
| 188 |
+
- split: year_2024
|
| 189 |
+
path: data/2024/Design/FINAL_PAIR_WEIGHT2024.parquet
|
| 190 |
+
- split: year_2025
|
| 191 |
+
path: data/2025/Design/FINAL_PAIR_WEIGHT2025.parquet
|
pipeline/hf_dataset_card_body.md
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NHIS 1997–2025 in Parquet (with dictionaries and linked mortality)
|
| 2 |
+
|
| 3 |
+
This dataset contains the public-use data files of the U.S. **National Health Interview Survey
|
| 4 |
+
(NHIS)** of the National Center for Health Statistics (NCHS), survey years **1997 through 2025**,
|
| 5 |
+
converted to Parquet: one Parquet file per original NCHS data file, under the NCHS file name.
|
| 6 |
+
It also includes:
|
| 7 |
+
|
| 8 |
+
- a **variable dictionary for each survey year**, built from the NCHS SAS input programs (column
|
| 9 |
+
positions, labels, value formats) and the NCHS codebooks (question text, universe, published
|
| 10 |
+
frequencies), with the observed count of every coded value;
|
| 11 |
+
- the **NCHS public-use linked mortality files** for NHIS 1997–2018 (follow-up through
|
| 12 |
+
31 December 2019);
|
| 13 |
+
- the imputed income files, paradata, supplements, injury/poisoning episode files, revised and
|
| 14 |
+
parent–child pair weights, and the NCHS dummy records for singleton PSUs.
|
| 15 |
+
|
| 16 |
+
Note on 2016: NCHS revised the 2016 weights in 2017. The 2016 ASCII files used here already carry
|
| 17 |
+
the revised weights (they equal the separately published `*_REVWTS` files, which are included as
|
| 18 |
+
published).
|
| 19 |
+
|
| 20 |
+
Built for the Bioanalysis R package. It works equally well with any tool that reads Parquet:
|
| 21 |
+
DuckDB, Arrow, Polars, pandas or R.
|
| 22 |
+
|
| 23 |
+
| | |
|
| 24 |
+
|---|---|
|
| 25 |
+
| Years | 29 (1997–2018 original design, 2019–2025 redesigned questionnaire) |
|
| 26 |
+
| Files | 457 Parquet data files plus 2 × 29 dictionary files |
|
| 27 |
+
| Rows | 28.2 million (0.37 GB of Parquet) |
|
| 28 |
+
| Persons (1997–2018 PERSONSX) | 2,061,980 |
|
| 29 |
+
| Sample adults (1997–2025) | 878,760 |
|
| 30 |
+
| Sample children (1997–2025) | 313,708 |
|
| 31 |
+
| Values | Original public-use codes; nothing recoded, imputed or dropped |
|
| 32 |
+
|
| 33 |
+
## Layout
|
| 34 |
+
|
| 35 |
+
```
|
| 36 |
+
data/<year>/<component>/<FILE>.parquet
|
| 37 |
+
data/<year>/Dictionary/VARIABLES.parquet one row per file x variable
|
| 38 |
+
data/<year>/Dictionary/VALUES.parquet one row per file x variable x code
|
| 39 |
+
metadata/FILES.parquet every file: rows, columns, grain, join keys, design variables, source URL, MD5
|
| 40 |
+
metadata/YEARS.parquet every year: design period, sample sizes, strata/PSU/weights, pooling guidance
|
| 41 |
+
metadata/VALIDATION.parquet every validation check: expected, observed, source
|
| 42 |
+
pipeline/ the R scripts that rebuilt everything from the NCHS sources
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
`<year>` is the survey year (`1997` … `2025`). File names are the NCHS data file names in upper case
|
| 46 |
+
(`PERSONSX`, `SAMADULT`, `ADULT19`, `CHILDINC24`, `INCMIMP3`, `NHIS_2010_MORT_2019_PUBLIC`, …).
|
| 47 |
+
`<component>` groups the NCHS file types:
|
| 48 |
+
|
| 49 |
+
| Component | NCHS files |
|
| 50 |
+
|---|---|
|
| 51 |
+
| `Core` | 1997–2018: `HOUSEHLD`, `FAMILYXX`, `PERSONSX`, `SAMADULT`, `SAMCHILD`; 2019+: `ADULTyy`, `CHILDyy` |
|
| 52 |
+
| `Supplement` | `IMMUNIZE` (1997–2003), `PREGSMKG`, `PREVADLT`, `PREVCHLD` (1998), `ALTHEALT`/`ALTVERBT` (2002), `ALTHEALT`/`CHILDCAM` (2007, 2012), `CANCERXX` (2005, 2010, 2015), `DISBTEST` (2009–2010), `QUALLIFE` (2010), `ADLTDISB`/`CHLDDISB` (2011–2012), `FMLYDISB`/`FUNCDISB` (2011–2017), `SC_BWTyy` (sample child birth weight, 2004–2010), `RATCAT07` (corrected 2007 poverty ratio) |
|
| 53 |
+
| `Injury` | `INJEPSOD`, `POIEPSOD` (1997–1999), `INJPOIEP` (2000–2017), `INJVERBT` (1997–2010) |
|
| 54 |
+
| `ImputedIncome` | `INCMIMP1`–`5` (1997–2018; `INCMAP1`–`5` in 2003–2004), `INCIMPS1`–`5` (top-coded supplemental files, 1997–2008), `ADULTINCyy`, `CHILDINCyy` (2019+, ten implicates stacked: `IMPNUM` in 2019–2020, `IMPNUM_A` / `IMPNUM_C` from 2021) |
|
| 55 |
+
| `Paradata` | `PARADATA` (2006–2018), `PARADATAyy` (2019+) |
|
| 56 |
+
| `Longitudinal` | `ADULTLONG20` (2019–2020 longitudinal weight `WTSA_L`), `ADULTPART20` (pooled 2019–2020 weight `WTSA_P`) |
|
| 57 |
+
| `Design` | `FINAL_PAIR_WEIGHTyyyy` (parent–child pair weights, 2019+), `*_REVWTS` (revised 2016 weights), `SAD_WGTS` (2010 Sample Adult × disability tests weight), `2003SAMCHILD`, `2005SAMCHILD`, `2007SAMCHILD`, `2007CHILDCAM` (NCHS dummy records for singleton PSUs, weight 1) |
|
| 58 |
+
| `Mortality` | `NHIS_<year>_MORT_2019_PUBLIC` (1997–2018) |
|
| 59 |
+
|
| 60 |
+
## Joining
|
| 61 |
+
|
| 62 |
+
**Within a year, 1997–2018.** Records are identified hierarchically:
|
| 63 |
+
|
| 64 |
+
- household: `HHX`;
|
| 65 |
+
- family: `HHX` + `FMX`;
|
| 66 |
+
- person: `HHX` + `FMX` + `FPX` (the person number is called `PX` in 1997–2003 files and in the
|
| 67 |
+
1997–2003 imputed income files; rename it to `FPX` to stack years);
|
| 68 |
+
- episode files add the episode number: `INJEPNO` / `POIEPNO` (1997–1999), `IPEPNO` (2000+);
|
| 69 |
+
- `IMMUNIZE` adds `IMRESPNO`; the imputed income files hold one implicate each (`IMPNUM`);
|
| 70 |
+
- the 2009 `DISBTEST` file spans the 2008 and 2009 interviews: its key includes `SRVY_YR`.
|
| 71 |
+
|
| 72 |
+
So `PERSONSX`, `SAMADULT`, `SAMCHILD`, the person-level supplements and `INCMIMPn` join on
|
| 73 |
+
`HHX + FMX + FPX` (or `PX`); `FAMILYXX` joins on `HHX + FMX`; `HOUSEHLD` on `HHX`. `HHX` is only
|
| 74 |
+
unique within a year: always join within a year (or include `SRVY_YR` in the key when stacking).
|
| 75 |
+
|
| 76 |
+
**Within a year, 2019+.** There is one sample adult and at most one sample child per household,
|
| 77 |
+
so every file joins on `HHX`. `ADULTINCyy` / `CHILDINCyy` have ten rows per `HHX` (one per
|
| 78 |
+
implicate: `IMPNUM` in 2019–2020, `IMPNUM_A` / `IMPNUM_C` from 2021; from 2021 the `ADULTyy` /
|
| 79 |
+
`CHILDyy` files also carry an `IMPNUM_A` / `IMPNUM_C` column, see the NCHS imputation
|
| 80 |
+
documentation). `FINAL_PAIR_WEIGHTyyyy` joins on `HHX`. `ADULTPART20` and
|
| 81 |
+
`ADULTLONG20` use `HHX_2020` (= `HHX` of `ADULT20`) and `ADULTLONG20` also carries `HHX_2019`
|
| 82 |
+
(= `HHX` of `ADULT19`): this is the only cross-year identity in the public files.
|
| 83 |
+
|
| 84 |
+
**Linked mortality.** The mortality files identify people by `PUBLICID`, a 14-character string that
|
| 85 |
+
NCHS builds as `SRVY_YR` (4) + `HHX` (6) + `FMX` (2) + `FPX` (2) of the 1997–2018 person files.
|
| 86 |
+
Values are kept as published, so join with
|
| 87 |
+
`substr(PUBLICID,1,4) = SRVY_YR, substr(PUBLICID,5,6) = HHX, substr(PUBLICID,11,2) = FMX,
|
| 88 |
+
substr(PUBLICID,13,2) = FPX` (or `PX` for 1997–2003). Mortality follow-up covers adults 18+
|
| 89 |
+
(`ELIGSTAT = 1` eligible); use `WGT_NEW` (person) or `SA_WGT_NEW` (sample adult), the weights NCHS
|
| 90 |
+
adjusted for ineligible records. The 1997–2014 files list every person of `PERSONSX`; the 2015–2018
|
| 91 |
+
files list sample adults and sample children only.
|
| 92 |
+
|
| 93 |
+
`metadata/FILES.parquet` gives the `grain` (checked on the data: one row per key, or several) and
|
| 94 |
+
`join_keys` of every file.
|
| 95 |
+
|
| 96 |
+
## Quick start
|
| 97 |
+
|
| 98 |
+
DuckDB (Python, R or CLI). No download is needed:
|
| 99 |
+
|
| 100 |
+
```python
|
| 101 |
+
import duckdb
|
| 102 |
+
con = duckdb.connect()
|
| 103 |
+
base = "hf://datasets/jamesjiadazhan/NHIS/data"
|
| 104 |
+
con.sql(f"""
|
| 105 |
+
SELECT a.HHX, a.AGEP_A, a.SEX_A, a.SMKCIGST_A, a.WTFA_A, a.PSTRAT, a.PPSU, i.FAMINCTC_A
|
| 106 |
+
FROM read_parquet('{base}/2019/Core/ADULT19.parquet') a
|
| 107 |
+
LEFT JOIN (SELECT * FROM read_parquet('{base}/2019/ImputedIncome/ADULTINC19.parquet')
|
| 108 |
+
WHERE IMPNUM = 1) i USING (HHX)
|
| 109 |
+
""").df()
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
1997–2018 person + sample adult + mortality:
|
| 113 |
+
|
| 114 |
+
```python
|
| 115 |
+
con.sql(f"""
|
| 116 |
+
SELECT s.HHX, s.FMX, s.FPX, s.AGE_P, s.SEX, s.WTFA_SA, s.STRAT_P, s.PSU_P,
|
| 117 |
+
m.ELIGSTAT, m.MORTSTAT, m.UCOD_LEADING, m.DODYEAR, m.SA_WGT_NEW
|
| 118 |
+
FROM read_parquet('{base}/2010/Core/SAMADULT.parquet') s
|
| 119 |
+
LEFT JOIN read_parquet('{base}/2010/Mortality/NHIS_2010_MORT_2019_PUBLIC.parquet') m
|
| 120 |
+
ON m.PUBLICID = CAST(s.SRVY_YR AS VARCHAR) || s.HHX || s.FMX || s.FPX
|
| 121 |
+
""").df()
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Dictionary lookup:
|
| 125 |
+
|
| 126 |
+
```python
|
| 127 |
+
con.sql(f"""
|
| 128 |
+
SELECT file, variable, label, question_text, universe
|
| 129 |
+
FROM read_parquet('{base}/2019/Dictionary/VARIABLES.parquet')
|
| 130 |
+
WHERE lower(label) LIKE '%cigarette%'
|
| 131 |
+
""").show()
|
| 132 |
+
con.sql(f"""
|
| 133 |
+
SELECT code, description, count_data, count_published
|
| 134 |
+
FROM read_parquet('{base}/2019/Dictionary/VALUES.parquet')
|
| 135 |
+
WHERE file = 'ADULT19' AND variable = 'SMKCIGST_A'
|
| 136 |
+
""").show()
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
R (arrow):
|
| 140 |
+
|
| 141 |
+
```r
|
| 142 |
+
library(arrow)
|
| 143 |
+
base <- "https://huggingface.co/datasets/jamesjiadazhan/NHIS/resolve/main/data"
|
| 144 |
+
adult <- read_parquet(file.path(base, "2019/Core/ADULT19.parquet"))
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
Hugging Face `datasets` (the configs listed above: dictionaries, linked mortality and pair weights,
|
| 148 |
+
each split by year):
|
| 149 |
+
|
| 150 |
+
```python
|
| 151 |
+
from datasets import load_dataset
|
| 152 |
+
mort = load_dataset("jamesjiadazhan/NHIS", "linked_mortality", split="year_2010")
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
## Survey design: required for every NHIS estimate
|
| 156 |
+
|
| 157 |
+
NHIS is a multistage area probability sample. Every estimate must use the weights and the public-use
|
| 158 |
+
design variables (Taylor linearization, PSUs treated as sampled with replacement, as NCHS
|
| 159 |
+
documents). `metadata/YEARS.parquet` lists them for every year:
|
| 160 |
+
|
| 161 |
+
| Years | Strata | PSU | Weights |
|
| 162 |
+
|---|---|---|---|
|
| 163 |
+
| 1997–2005 | `STRATUM` | `PSU` | `WTFA_HH` (household), `WTFA_FAM` (family), `WTFA` (person), `WTFA_SA` (sample adult), `WTFA_SC` (sample child), supplement-specific weights |
|
| 164 |
+
| 2006–2015 | `STRAT_P` | `PSU_P` | as above |
|
| 165 |
+
| 2016–2018 | `PSTRAT` | `PPSU` | as above |
|
| 166 |
+
| 2019–2025 | `PSTRAT` | `PPSU` | `WTFA_A` (sample adult), `WTFA_C` (sample child); 2019 also `WTIA_A`/`WTIA_C`; 2020 `WTSA_P`, `WTSA_L`; `final_pair_weight` (parent–child pairs) |
|
| 167 |
+
|
| 168 |
+
- In R: `survey::svydesign(ids = ~PPSU, strata = ~PSTRAT, weights = ~WTFA_A, nest = TRUE, data = adult)`.
|
| 169 |
+
- Use the weight of the file the variables come from (person, sample adult, sample child,
|
| 170 |
+
supplement); the imputed income files carry no weights, join them to the file whose weight you use
|
| 171 |
+
and combine the implicates with Rubin's rules.
|
| 172 |
+
- **Pooling years** (NCHS variance estimation guidance, see sources): divide each weight by the
|
| 173 |
+
number of years pooled.
|
| 174 |
+
- Years within one sample design period (1997–2005, 2006–2015, 2016–2018) are pooled as one
|
| 175 |
+
sample with that period's design variables; do not treat the years as independent.
|
| 176 |
+
- Across design periods (2005/2006, 2015/2016), treat the periods as independent and create a
|
| 177 |
+
stratum variable with distinct values per period (for example, add 1000 to the 2016+
|
| 178 |
+
`PSTRAT`), because the codes are not related across periods.
|
| 179 |
+
- 2019 and later: NCHS states that public-use files from 2019 on, including 2025 (first year of
|
| 180 |
+
the 2025 sample redesign), can be pooled with `PSTRAT`/`PPSU` as they are. For pooled 2019–2020
|
| 181 |
+
sample adult estimates use `WTSA_P` (`ADULTPART20`) for the 2020 records.
|
| 182 |
+
- The 2019 questionnaire, file structure and weighting changed: pooling 1997–2018 with 2019+ data
|
| 183 |
+
needs harmonised variables and care; NCHS gives no public-use recipe for it.
|
| 184 |
+
- The 2025 files are smaller: NCHS reports budget-driven sample reductions in the first year of the
|
| 185 |
+
2025 design and a data-collection pause from 1 October to 17 November 2025.
|
| 186 |
+
- Singleton PSUs: 2003, 2005 and 2007 sample child (and 2007 child CAM) files contain PSUs with a
|
| 187 |
+
single respondent. NCHS published dummy records (`Design/2003SAMCHILD` etc., weight 1) that can be
|
| 188 |
+
appended for software that cannot handle them; or use `options(survey.lonely.psu = "adjust")`.
|
| 189 |
+
|
| 190 |
+
## Sources and processing
|
| 191 |
+
|
| 192 |
+
| Part | Source | Processing |
|
| 193 |
+
|---|---|---|
|
| 194 |
+
| 1997–2018 data | [NCHS FTP `Datasets/NHIS/<year>`](https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/NHIS/) fixed-width ASCII | Read with the column positions of the NCHS SAS input program (`Program_Code/NHIS/<year>`); `$` variables as text, others as numbers |
|
| 195 |
+
| 2019–2025 data | NCHS CSV files (`*csv.zip`) | Variable order and types from the NCHS SAS program; the CSV is used because the ASCII copy rounds weights to its field width (e.g. `WTFA_A` 13177.008 vs 13177.01) |
|
| 196 |
+
| Imputed income 1997–2004 | `Datasets/NHIS/<year>_imputed_income` | No SAS program on the FTP: layout of the 2005 `INCMIMP.sas`, which is identical to the NCHS dataset documentation `datdocYY.pdf` (person number `PX` through 2003) |
|
| 197 |
+
| Pair weights | NCHS SAS data sets (`final_pair_weightYYYY.sas7bdat`) | `haven::read_sas` |
|
| 198 |
+
| 2016 revised weights | NCHS CSV (`2016/RWCSV`) | IDs as text, weights as numbers |
|
| 199 |
+
| Linked mortality | [NCHS public-use linked mortality files](https://www.cdc.gov/nchs/linked-data/mortality-files/index.html) | NHIS layout of the NCHS `SAS_ReadInProgramAllSurveys.sas` |
|
| 200 |
+
| Dictionaries | NCHS SAS programs + codebooks | See below |
|
| 201 |
+
|
| 202 |
+
Reading rules (exactly what the NCHS SAS programs do): blank numeric fields and `.` are missing;
|
| 203 |
+
implied decimals of the INPUT statement (`WTFA 22-29 .3`) are applied only when the field has no
|
| 204 |
+
decimal point; blank character fields are null; leading and trailing blanks of character fields
|
| 205 |
+
are removed. Nothing is recoded, top-coded, imputed or dropped. The SAS programs are parsed as text;
|
| 206 |
+
nothing downloaded is executed.
|
| 207 |
+
|
| 208 |
+
**Dictionaries.** `VARIABLES.parquet` (year, component, file, variable, position, start, end,
|
| 209 |
+
width, implied_decimals, type, label, sas_format, n_nonmissing, n_distinct, label_source,
|
| 210 |
+
question_id, question_text, universe, universe_description, sources, recodes, keywords, notes,
|
| 211 |
+
module, section, in_codebook, codebook) and `VALUES.parquet` (year, component, file, variable, code,
|
| 212 |
+
description, count_data, value_source, sas_format, count_published, value_order):
|
| 213 |
+
|
| 214 |
+
- labels, positions and value labels come from the NCHS SAS programs (`label_source`);
|
| 215 |
+
- question text, universe and notes come from the NCHS codebooks: the 1997–2003 codebooks
|
| 216 |
+
(`<file>.pdf`), the 2004–2018 layout documents (`<file>_layout.pdf`) and the 2019+ codebooks
|
| 217 |
+
(`<File>-codebook.pdf`), parsed from their text (`codebook` names the document);
|
| 218 |
+
- `count_published` is the unweighted frequency printed in the 1997–2003 and 2019+ codebooks;
|
| 219 |
+
`count_data` is the count in the Parquet file (ranges such as `01-25` are summed; open ranges
|
| 220 |
+
such as `LOW-HIGH` have none). `value_source = "codebook"` marks categories that appear only
|
| 221 |
+
in the codebook (for example `<Blank: Not in universe>`).
|
| 222 |
+
|
| 223 |
+
**Dictionary coverage.** 64,117 file × variable rows: 64,095 have a label, 53,473 are matched to a
|
| 224 |
+
codebook entry (45,543 with question text, 52,491 with a universe). 361,719 value rows, of which
|
| 225 |
+
123,643 carry a published frequency (1997–2003 and 2019–2025). Files without a codebook (labels
|
| 226 |
+
and value formats from the SAS program only): imputed income files, linked mortality, revised
|
| 227 |
+
weights, pair weights (labels of the SAS data set), birth weight `SC_BWT`, `RATCAT07`, `SAD_WGTS`
|
| 228 |
+
and the 2006 paradata. 2004–2018 layout documents carry no frequencies, so `count_published` is
|
| 229 |
+
empty for those years (`count_data` is always filled).
|
| 230 |
+
|
| 231 |
+
**Validation** (`pipeline/05_validate.R`; every check with its source is in `metadata/VALIDATION.parquet`):
|
| 232 |
+
|
| 233 |
+
- **825 checks, all passed.**
|
| 234 |
+
- Row counts: 223 files equal the record count printed by NCHS (1997–2003 codebook headers,
|
| 235 |
+
`RECTYPE` frequencies of the 2004–2018 frequency reports and 2019+ codebooks); the 2019–2024
|
| 236 |
+
Sample Adult / Sample Child files equal the interviewed counts of Table 2 of the 2024 Survey
|
| 237 |
+
Description (2020: `ADULTPART20` = 21,153; `ADULT20` also holds the 10,415 re-interviewed 2019
|
| 238 |
+
adults).
|
| 239 |
+
- Published frequencies: all 123,643 published unweighted frequencies equal the counts in the
|
| 240 |
+
Parquet files (87 files).
|
| 241 |
+
- Layout: every fixed-width record fits the SAS layout and no numeric field failed to parse
|
| 242 |
+
(406 files).
|
| 243 |
+
- Second NCHS copy: 71 files of 2015–2025 agree cell by cell with the other format NCHS
|
| 244 |
+
publishes (1997–2018 Parquet vs the CSV copy; 2019+ Parquet vs the ASCII copy, within the
|
| 245 |
+
ASCII rounding). Two NCHS differences are explained, not errors: the 2015–2018 CSV copies store
|
| 246 |
+
`BMI` without its implied decimals (2358 for 23.58), and the 2016 Sample Child CSV copy has the
|
| 247 |
+
original weights while the ASCII file (used here) has the revised 2016 weights (all 2016 ASCII
|
| 248 |
+
core files equal the `*_REVWTS` files). In 2021 `PARADATA21`, 11 character flags are `.` in the
|
| 249 |
+
ASCII copy and blank in the CSV.
|
| 250 |
+
- Linked mortality: every `PUBLICID` of the 22 files matches one person of the same year's
|
| 251 |
+
`PERSONSX`. 1997–2014 files cover all persons; 2015–2018 files cover sample adults and sample
|
| 252 |
+
children only, as NCHS released them.
|
| 253 |
+
- Published estimates, reproduced with `survey` (Taylor series, `PSU` nested in strata, lonely
|
| 254 |
+
PSU "adjust"): current cigarette smoking among adults, 2005 20.90% (published 20.9%,
|
| 255 |
+
MMWR 2006;55:1145), 2010 19.35% (19.3%, MMWR 2011;60:1207), 2018 13.73% (13.7%,
|
| 256 |
+
MMWR 2019;68:1013), 2019 13.98% (14.0%, MMWR 2020;69:1736).
|
| 257 |
+
|
| 258 |
+
**Coverage.** Every data file in the NCHS FTP folders `Datasets/NHIS/1997` … `2025` and the
|
| 259 |
+
`<year>_imputed_income` and `2006_paradata` folders, and the NHIS linked mortality files for
|
| 260 |
+
1997–2018. Not included: survey years 1963–1996 (different file structures), CSV copies of the
|
| 261 |
+
same files, the restricted-use files of the NCHS Research Data Center, and IPUMS NHIS (its terms
|
| 262 |
+
do not allow redistribution).
|
| 263 |
+
|
| 264 |
+
## Licence and citation
|
| 265 |
+
|
| 266 |
+
- **NHIS and linked mortality:** NCHS public-use data, U.S. Government works in the public domain
|
| 267 |
+
("…is in the public domain, and may be freely used or reproduced without obtaining copyright
|
| 268 |
+
permission", [CDC](https://www.cdc.gov/other/agencymaterials.html)). Cite: National Center for
|
| 269 |
+
Health Statistics. *National Health Interview Survey, <year>.* Public-use data file and
|
| 270 |
+
documentation. Hyattsville, MD: NCHS, Centers for Disease Control and Prevention.
|
| 271 |
+
- This compilation (pipeline, dictionaries, layout) is released under CC0-1.0.
|
| 272 |
+
|
| 273 |
+
Data users must follow the [NCHS data use agreement](https://www.cdc.gov/nchs/data_access/restrictions.htm):
|
| 274 |
+
use the data for statistical reporting and analysis only, make no attempt to learn the identity of
|
| 275 |
+
any person or household, and do not link the data with individually identifiable data from other
|
| 276 |
+
NCHS or non-NCHS datasets.
|
pipeline/readers.R
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# readers.R: read NHIS source files exactly as the NCHS programs define them
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# Shared by 03_convert.R and 05_validate.R:
|
| 5 |
+
# materialise() extract a ZIP member to a temporary folder
|
| 6 |
+
# sas_numeric() SAS column-input conversion of numeric fields (blank or
|
| 7 |
+
# "." = missing; implied decimals only without a point)
|
| 8 |
+
# read_fixed() fixed-width ASCII file with a parsed SAS layout
|
| 9 |
+
# read_csv_layout() NCHS CSV (2019+) with the SAS program's order and types
|
| 10 |
+
# read_revwts() 2016 revised-weights CSV (IDs as text)
|
| 11 |
+
# =============================================================================
|
| 12 |
+
|
| 13 |
+
# Extract a ZIP member (or return the plain file) to a temporary location.
|
| 14 |
+
materialise <- function(r) {
|
| 15 |
+
if (is.na(r$member)) {
|
| 16 |
+
return(list(path = r$archive, cleanup = character()))
|
| 17 |
+
}
|
| 18 |
+
td <- tempfile(paste0(r$year, "_", r$file, "_"), tmpdir = tmp_root)
|
| 19 |
+
dir.create(td)
|
| 20 |
+
utils::unzip(r$archive, files = r$member, exdir = td, junkpaths = TRUE)
|
| 21 |
+
list(path = file.path(td, basename(r$member)), cleanup = td)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
# Convert the text fields of one numeric column as SAS column input would.
|
| 25 |
+
sas_numeric <- function(x, decimals) {
|
| 26 |
+
x <- trimws(x)
|
| 27 |
+
x[x %in% c("", ".")] <- NA
|
| 28 |
+
v <- suppressWarnings(as.numeric(x))
|
| 29 |
+
bad <- sum(!is.na(x) & is.na(v))
|
| 30 |
+
if (decimals > 0) {
|
| 31 |
+
implied <- !is.na(v) & !grepl(".", x, fixed = TRUE)
|
| 32 |
+
v[implied] <- v[implied] / 10^decimals
|
| 33 |
+
}
|
| 34 |
+
attr(v, "bad") <- bad
|
| 35 |
+
v
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
# Read a fixed-width file with a parsed SAS layout; returns data + checks.
|
| 39 |
+
read_fixed <- function(path, lay) {
|
| 40 |
+
lines <- readLines(path, warn = FALSE, encoding = "latin1")
|
| 41 |
+
lines <- sub("\r$", "", lines)
|
| 42 |
+
lines <- lines[nchar(lines) > 0]
|
| 43 |
+
reclen <- range(nchar(lines, type = "bytes"))
|
| 44 |
+
d <- readr::read_fwf(I(paste0(lines, "\n", collapse = "")),
|
| 45 |
+
col_positions = readr::fwf_positions(lay$start, lay$end, lay$variable),
|
| 46 |
+
col_types = readr::cols(.default = readr::col_character()),
|
| 47 |
+
trim_ws = FALSE, na = character(), progress = FALSE,
|
| 48 |
+
locale = readr::locale(encoding = "latin1")
|
| 49 |
+
)
|
| 50 |
+
d <- as.data.frame(d, stringsAsFactors = FALSE)
|
| 51 |
+
bad <- integer(0)
|
| 52 |
+
for (j in seq_len(nrow(lay))) {
|
| 53 |
+
v <- lay$variable[j]
|
| 54 |
+
if (lay$char[j]) {
|
| 55 |
+
x <- trimws(d[[v]])
|
| 56 |
+
x[!is.na(x) & x == ""] <- NA
|
| 57 |
+
d[[v]] <- x
|
| 58 |
+
} else {
|
| 59 |
+
x <- sas_numeric(d[[v]], lay$decimals[j])
|
| 60 |
+
if (attr(x, "bad") > 0) bad[v] <- attr(x, "bad")
|
| 61 |
+
attr(x, "bad") <- NULL
|
| 62 |
+
d[[v]] <- x
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
list(data = d, reclen = reclen, bad = bad, nlines = length(lines))
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
# Read an NCHS CSV file (2019+) with the variable order and types of the
|
| 69 |
+
# NCHS SAS program; columns not in the program are kept at the end.
|
| 70 |
+
read_csv_layout <- function(path, lay) {
|
| 71 |
+
d <- utils::read.csv(path, colClasses = "character", check.names = FALSE, na.strings = character())
|
| 72 |
+
names(d) <- toupper(names(d))
|
| 73 |
+
miss <- setdiff(lay$variable, names(d))
|
| 74 |
+
if (length(miss)) stop("variables of the SAS program missing from the CSV: ", paste(utils::head(miss, 10), collapse = " "))
|
| 75 |
+
extra <- setdiff(names(d), lay$variable)
|
| 76 |
+
d <- d[c(lay$variable, extra)]
|
| 77 |
+
bad <- integer(0)
|
| 78 |
+
for (v in names(d)) {
|
| 79 |
+
if (v %in% lay$variable[lay$char]) {
|
| 80 |
+
x <- trimws(d[[v]])
|
| 81 |
+
x[x == ""] <- NA
|
| 82 |
+
d[[v]] <- x
|
| 83 |
+
} else {
|
| 84 |
+
x <- sas_numeric(d[[v]], 0)
|
| 85 |
+
if (attr(x, "bad") > 0) bad[v] <- attr(x, "bad")
|
| 86 |
+
attr(x, "bad") <- NULL
|
| 87 |
+
d[[v]] <- x
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
list(data = d, reclen = c(NA, NA), bad = bad, extra = extra)
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
# Read a 2016 revised-weights CSV: IDs as text, other columns numeric.
|
| 94 |
+
read_revwts <- function(path) {
|
| 95 |
+
d <- utils::read.csv(path, colClasses = "character", check.names = FALSE)
|
| 96 |
+
names(d) <- toupper(names(d))
|
| 97 |
+
for (v in setdiff(names(d), c("HHX", "FMX", "FPX"))) d[[v]] <- sas_numeric(d[[v]], 0)
|
| 98 |
+
for (v in names(d)) attr(d[[v]], "bad") <- NULL
|
| 99 |
+
lay <- data.frame(
|
| 100 |
+
variable = names(d), position = seq_along(d), start = NA_integer_, end = NA_integer_,
|
| 101 |
+
width = NA_integer_, decimals = 0L,
|
| 102 |
+
type = ifelse(names(d) %in% c("HHX", "FMX", "FPX"), "string", "double"),
|
| 103 |
+
label = unname(c(
|
| 104 |
+
HHX = "Household Number", FMX = "Family Number",
|
| 105 |
+
FPX = "Person Number (Within family)"
|
| 106 |
+
)[names(d)]),
|
| 107 |
+
format = NA_character_, stringsAsFactors = FALSE
|
| 108 |
+
)
|
| 109 |
+
list(data = d, layout = lay)
|
| 110 |
+
}
|
| 111 |
+
|
pipeline/sas_setup.R
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# sas_setup.R: parse NCHS SAS input programs (layout, labels, value formats)
|
| 3 |
+
# =============================================================================
|
| 4 |
+
# The NHIS public-use ASCII files are documented by NCHS SAS programs
|
| 5 |
+
# (Program_Code/NHIS/<year>/<file>.sas, the imputed income folders and the
|
| 6 |
+
# linked mortality read-in program). This file reads such a program as text
|
| 7 |
+
# (it is never executed) and returns
|
| 8 |
+
# layout : variable, position (order), start, end, width, type
|
| 9 |
+
# (character / numeric), implied decimals, label, format name
|
| 10 |
+
# formats: format name, code (range text as written), label
|
| 11 |
+
# Used by 03_convert.R (fixed-width reading) and 04_dictionary.R.
|
| 12 |
+
# Statements parsed: PROC FORMAT VALUE, LENGTH, INPUT (column input
|
| 13 |
+
# "VAR [$] start[-end] [.d]"), LABEL and FORMAT. Comments are removed first.
|
| 14 |
+
# =============================================================================
|
| 15 |
+
|
| 16 |
+
# Read a program as UTF-8 text (NCHS programs are Windows-1252 encoded).
|
| 17 |
+
read_sas_text <- function(path) {
|
| 18 |
+
raw <- readBin(path, "raw", file.size(path))
|
| 19 |
+
raw <- raw[raw != as.raw(0) & raw != as.raw(0x1a)]
|
| 20 |
+
txt <- rawToChar(raw)
|
| 21 |
+
if (!validUTF8(txt)) txt <- iconv(txt, "CP1252", "UTF-8", sub = "?")
|
| 22 |
+
gsub("\r", "", txt, fixed = TRUE)
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
# Split SAS text into statements, dropping /* */ and * ...; comments while
|
| 26 |
+
# respecting quoted strings (semicolons inside labels are kept).
|
| 27 |
+
sas_statements <- function(txt) {
|
| 28 |
+
# Lexical pieces: block comments, quoted strings, semicolons, other text.
|
| 29 |
+
rx <- "/\\*[\\s\\S]*?\\*/|\"[^\"]*\"|'[^']*'|;|[^;\"'/]+|/"
|
| 30 |
+
pc <- regmatches(txt, gregexpr(rx, txt, perl = TRUE))[[1]]
|
| 31 |
+
pc[startsWith(pc, "/*")] <- " "
|
| 32 |
+
semi <- pc == ";"
|
| 33 |
+
id <- cumsum(c(0, utils::head(semi, -1)))
|
| 34 |
+
st <- vapply(split(pc[!semi], id[!semi]), paste, "", collapse = "")
|
| 35 |
+
st <- trimws(gsub("[[:space:]]+", " ", st))
|
| 36 |
+
# Comment statements start with "*" (e.g. "* DEFINE LENGTHS").
|
| 37 |
+
st[nzchar(st) & !startsWith(st, "*")]
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
# First keyword of a statement, upper case.
|
| 41 |
+
stmt_key <- function(s) toupper(sub("^([A-Za-z]+).*", "\\1", s))
|
| 42 |
+
|
| 43 |
+
# Tokenise a statement body: quoted strings, format names (ending in "."),
|
| 44 |
+
# implied-decimal markers (.d), numbers, words and the symbols $ - = @.
|
| 45 |
+
sas_tokens <- function(s) {
|
| 46 |
+
rx <- paste0(
|
| 47 |
+
"\"[^\"]*\"|'[^']*'|\\$?[A-Za-z_][A-Za-z0-9_]*\\.[0-9]*|\\.[0-9]+|",
|
| 48 |
+
"[0-9]+\\.?[0-9]*|[A-Za-z_&][A-Za-z0-9_.&]*|\\$|-|=|@|<|\\(|\\)|,|\\."
|
| 49 |
+
)
|
| 50 |
+
regmatches(s, gregexpr(rx, s, perl = TRUE))[[1]]
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
# Remove surrounding quotes and doubled quotes inside a SAS string literal.
|
| 54 |
+
unquote <- function(x) {
|
| 55 |
+
q <- substr(x, 1, 1)
|
| 56 |
+
is_q <- q %in% c("\"", "'") & nchar(x) >= 2
|
| 57 |
+
x[is_q] <- substr(x[is_q], 2, nchar(x[is_q]) - 1)
|
| 58 |
+
x <- gsub("\"\"", "\"", x, fixed = TRUE)
|
| 59 |
+
gsub("''", "'", x, fixed = TRUE)
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
# Parse one VALUE statement into (format, code, label) rows.
|
| 63 |
+
parse_value <- function(s) {
|
| 64 |
+
body <- sub("^VALUE\\s+", "", s, ignore.case = TRUE)
|
| 65 |
+
name <- toupper(sub("^(\\$?[A-Za-z_][A-Za-z0-9_]*).*", "\\1", body))
|
| 66 |
+
rest <- substring(body, nchar(name) + 1)
|
| 67 |
+
# range = "label" pairs; the range is everything up to the "=".
|
| 68 |
+
rx <- "([^=]+?)\\s*=\\s*(\"(?:[^\"]|\"\")*\"|'(?:[^']|'')*')"
|
| 69 |
+
m <- regmatches(rest, gregexpr(rx, rest, perl = TRUE))[[1]]
|
| 70 |
+
if (!length(m)) {
|
| 71 |
+
return(NULL)
|
| 72 |
+
}
|
| 73 |
+
p <- regmatches(m, regexec(rx, m, perl = TRUE))
|
| 74 |
+
code <- trimws(vapply(p, `[`, "", 2))
|
| 75 |
+
code <- sub("^\\(.*?\\)\\s*", "", code) # format options such as (multilabel)
|
| 76 |
+
data.frame(
|
| 77 |
+
format = name, code = unquote(gsub("^\\s+|\\s+$", "", code)),
|
| 78 |
+
code_raw = code, label = unquote(vapply(p, `[`, "", 3)),
|
| 79 |
+
stringsAsFactors = FALSE
|
| 80 |
+
)
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
# Parse the INPUT statement (column input) into a layout table.
|
| 84 |
+
parse_input <- function(s) {
|
| 85 |
+
tk <- sas_tokens(sub("^INPUT\\s*", "", s, ignore.case = TRUE))
|
| 86 |
+
res <- list()
|
| 87 |
+
i <- 1
|
| 88 |
+
n <- length(tk)
|
| 89 |
+
# Token tests: SAS variable name / integer column number.
|
| 90 |
+
is_name <- function(t) grepl("^[A-Za-z_][A-Za-z0-9_]*$", t)
|
| 91 |
+
is_int <- function(t) grepl("^[0-9]+$", t)
|
| 92 |
+
while (i <= n) {
|
| 93 |
+
t <- tk[i]
|
| 94 |
+
if (t == "@") {
|
| 95 |
+
stop("pointer (@) input is not supported: ", paste(tk[i:min(n, i + 3)], collapse = " "))
|
| 96 |
+
}
|
| 97 |
+
if (!is_name(t)) {
|
| 98 |
+
i <- i + 1
|
| 99 |
+
next
|
| 100 |
+
}
|
| 101 |
+
var <- toupper(t)
|
| 102 |
+
i <- i + 1
|
| 103 |
+
char <- FALSE
|
| 104 |
+
if (i <= n && tk[i] == "$") {
|
| 105 |
+
char <- TRUE
|
| 106 |
+
i <- i + 1
|
| 107 |
+
}
|
| 108 |
+
if (i > n || !is_int(tk[i])) stop("unexpected token after ", var, ": ", tk[i])
|
| 109 |
+
start <- as.integer(tk[i])
|
| 110 |
+
end <- start
|
| 111 |
+
i <- i + 1
|
| 112 |
+
if (i + 1 <= n && tk[i] == "-" && is_int(tk[i + 1])) {
|
| 113 |
+
end <- as.integer(tk[i + 1])
|
| 114 |
+
i <- i + 2
|
| 115 |
+
}
|
| 116 |
+
dec <- 0L
|
| 117 |
+
if (i <= n && grepl("^\\.[0-9]+$", tk[i])) {
|
| 118 |
+
dec <- as.integer(substring(tk[i], 2))
|
| 119 |
+
i <- i + 1
|
| 120 |
+
}
|
| 121 |
+
res[[length(res) + 1]] <- data.frame(
|
| 122 |
+
variable = var, start = start, end = end, char = char, decimals = dec,
|
| 123 |
+
stringsAsFactors = FALSE
|
| 124 |
+
)
|
| 125 |
+
}
|
| 126 |
+
do.call(rbind, res)
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
# Parse LABEL statements: VAR = "text" pairs.
|
| 130 |
+
parse_labels <- function(s) {
|
| 131 |
+
body <- sub("^LABEL\\s*", "", s, ignore.case = TRUE)
|
| 132 |
+
rx <- "([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(\"(?:[^\"]|\"\")*\"|'(?:[^']|'')*')"
|
| 133 |
+
m <- regmatches(body, gregexpr(rx, body, perl = TRUE))[[1]]
|
| 134 |
+
if (!length(m)) {
|
| 135 |
+
return(NULL)
|
| 136 |
+
}
|
| 137 |
+
p <- regmatches(m, regexec(rx, m, perl = TRUE))
|
| 138 |
+
data.frame(
|
| 139 |
+
variable = toupper(vapply(p, `[`, "", 2)), label = unquote(vapply(p, `[`, "", 3)),
|
| 140 |
+
stringsAsFactors = FALSE
|
| 141 |
+
)
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
# Parse FORMAT statements: one or more variables followed by a format name.
|
| 145 |
+
parse_format_assoc <- function(s) {
|
| 146 |
+
tk <- sas_tokens(sub("^FORMAT\\s*", "", s, ignore.case = TRUE))
|
| 147 |
+
vars <- character()
|
| 148 |
+
out <- list()
|
| 149 |
+
for (t in tk) {
|
| 150 |
+
if (grepl("^\\$?[A-Za-z_][A-Za-z0-9_]*\\.[0-9]*$", t)) {
|
| 151 |
+
if (length(vars)) {
|
| 152 |
+
out[[length(out) + 1]] <- data.frame(
|
| 153 |
+
variable = toupper(vars), format = toupper(sub("\\.[0-9]*$", "", t)),
|
| 154 |
+
stringsAsFactors = FALSE
|
| 155 |
+
)
|
| 156 |
+
}
|
| 157 |
+
vars <- character()
|
| 158 |
+
} else if (grepl("^[A-Za-z_][A-Za-z0-9_]*$", t)) {
|
| 159 |
+
vars <- c(vars, t)
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
do.call(rbind, out)
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
# Parse a whole program (or a text section of it); returns list(layout,
|
| 166 |
+
# formats, n_input). Labels and formats are matched to the INPUT variables.
|
| 167 |
+
parse_sas_program <- function(path, section = NULL) {
|
| 168 |
+
txt <- read_sas_text(path)
|
| 169 |
+
if (!is.null(section)) txt <- section(txt)
|
| 170 |
+
st <- sas_statements(txt)
|
| 171 |
+
key <- vapply(st, stmt_key, "", USE.NAMES = FALSE)
|
| 172 |
+
fm <- do.call(rbind, lapply(st[key == "VALUE"], parse_value))
|
| 173 |
+
inp <- st[key == "INPUT"]
|
| 174 |
+
if (!length(inp)) stop("no INPUT statement in ", path)
|
| 175 |
+
lay <- do.call(rbind, lapply(inp, parse_input))
|
| 176 |
+
lab <- do.call(rbind, lapply(st[key == "LABEL"], parse_labels))
|
| 177 |
+
fa <- do.call(rbind, lapply(st[key == "FORMAT"], parse_format_assoc))
|
| 178 |
+
# Character variables are declared with "$" in INPUT or in LENGTH.
|
| 179 |
+
len_char <- unlist(lapply(st[key == "LENGTH"], function(z) {
|
| 180 |
+
m <- regmatches(z, gregexpr("([A-Za-z_][A-Za-z0-9_]*)\\s*\\$", z))[[1]]
|
| 181 |
+
toupper(trimws(sub("\\$$", "", m)))
|
| 182 |
+
}))
|
| 183 |
+
lay$char <- lay$char | lay$variable %in% len_char
|
| 184 |
+
lay$position <- seq_len(nrow(lay))
|
| 185 |
+
lay$width <- lay$end - lay$start + 1L
|
| 186 |
+
lay$type <- ifelse(lay$char, "string", "double")
|
| 187 |
+
lay$label <- if (is.null(lab)) NA_character_ else lab$label[match(lay$variable, lab$variable)]
|
| 188 |
+
lay$format <- if (is.null(fa)) NA_character_ else fa$format[match(lay$variable, fa$variable)]
|
| 189 |
+
if (!is.null(fm)) fm <- fm[!duplicated(fm[c("format", "code_raw")]), ]
|
| 190 |
+
list(layout = lay, formats = fm, n_input = length(inp))
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
# Section of the NCHS linked mortality read-in program that defines NHIS.
|
| 194 |
+
mortality_nhis_section <- function(txt) {
|
| 195 |
+
a <- regexpr("\\*NHIS VERSION\\*", txt)
|
| 196 |
+
b <- regexpr("\\*NHANES VERSION\\*", txt)
|
| 197 |
+
if (a < 0) stop("NHIS section not found in mortality program")
|
| 198 |
+
if (b < a) b <- nchar(txt) + 1
|
| 199 |
+
substr(txt, a + attr(a, "match.length"), b - 1)
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
# Section of sam_disb.sas (2010) that reads SAD_WGTS.DAT.
|
| 203 |
+
sad_wgts_section <- function(txt) {
|
| 204 |
+
a <- regexpr("DATA SAD_WGTS;", txt, fixed = TRUE)
|
| 205 |
+
if (a < 0) stop("SAD_WGTS data step not found")
|
| 206 |
+
rest <- substring(txt, a)
|
| 207 |
+
b <- regexpr("RUN;", rest, fixed = TRUE)
|
| 208 |
+
substr(rest, 1, b + 3)
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
# Section functions by name (files_spec.R column "section").
|
| 212 |
+
section_fun <- function(name) {
|
| 213 |
+
if (is.na(name) || name == "incmimp_px") {
|
| 214 |
+
return(NULL)
|
| 215 |
+
}
|
| 216 |
+
switch(name,
|
| 217 |
+
mortality = mortality_nhis_section,
|
| 218 |
+
sad_wgts = sad_wgts_section,
|
| 219 |
+
stop("unknown section ", name)
|
| 220 |
+
)
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
# Layout for one inventory row (adds the PX rename for 1997-2003 INCMIMP).
|
| 224 |
+
program_layout <- function(program, section) {
|
| 225 |
+
p <- parse_sas_program(program, section_fun(section))
|
| 226 |
+
if (!is.na(section) && section == "incmimp_px") {
|
| 227 |
+
p$layout$variable[p$layout$variable == "FPX"] <- "PX"
|
| 228 |
+
}
|
| 229 |
+
p
|
| 230 |
+
}
|