Commit 7b7b7a8a authored by Paul McCarthy's avatar Paul McCarthy 🚵
Browse files

Merge branch 'rf/icd10_bad_codes' into 'master'

Rf/icd10 bad codes

See merge request fsl/ukbparse!118
parents ff027057 23af00fc
......@@ -2,6 +2,30 @@
======================
0.19.0 (Wednesday 24th April 2019)
----------------------------------
Added
^^^^^
* The ``--column`` option now accepts a file which contains a list of column
names to import.
Changed
^^^^^^^
* The :func:`.icd10.codeToNumeric` and :func:`.icd10.numericToCode` functions
have been changed to use the integer node IDs in the ICD10 hierarchy
file. The previous approach could not handle parent categories, nor a small
number of ICD10 codes which do not have a ``<letter><number>`` structure.
* The :func:`.fileinfo.has_header` function has been made more lenient for
files with a small number of columns.
0.18.0 (Tuesday 23rd April 2019)
--------------------------------
......
......@@ -6,7 +6,7 @@
#
__version__ = '0.18.0'
__version__ = '0.19.0'
"""The ``ukbparse`` versioning scheme roughly follows Semantic Versioning
conventions.
"""
......
......@@ -11,6 +11,7 @@ arguments and configuration files.
import os.path as op
import functools as ft
import itertools as it
import multiprocessing as mp
import sys
import glob
......@@ -265,9 +266,10 @@ CLI_ARGUMENT_HELP = {
'--remove_unknown.',
'column' :
'Name of column to import. Can also be a glob-style wildcard pattern - '
'columns with a name matching the pattern will be imported. Can be used '
'multiple times. Implies --remove_unknown.',
'Name of column to import, or file containing a list of column names. Can '
'also be a glob-style wildcard pattern - columns with a name matching the '
'pattern will be imported. Can be used multiple times. Implies '
'--remove_unknown.',
'category' :
'Category ID or label to import. Can be used multiple times. Implies '
......@@ -699,6 +701,20 @@ def parseArgs(argv=None, namespace=None):
if args.variable is not None: args.variable = replaceIDs(args.variable)[0]
if args.exclude is not None: args.exclude = replaceIDs(args.exclude)[0]
# The column option accepts
# column names, or a file
# containing column names
def loadIfExists(path):
if op.exists(path):
with open(path, 'rt') as f:
items = f.readlines()
else:
items = [path]
return [i.strip() for i in items]
if args.column is not None:
args.column = list(it.chain(*[loadIfExists(c) for c in args.column]))
# visits are restricted using the
# keepVisits cleaning function
if args.visit is not None:
......
......@@ -138,7 +138,16 @@ def has_header(sample,
if (hist[t0] / len(ctypes)) < thres: colcount += 1
else: colcount -= 1
return colcount > 0
# If more columns than not passed
# the threshold, let's say we have
# a header. But be lenient at low
# column counts.
threshold = collections.defaultdict(lambda : 1)
threshold[2] = 0
threshold[4] = 0
threshold[6] = 0
return colcount >= threshold[len(coltypes)]
def sniff(datafile):
......
......@@ -149,6 +149,12 @@ class Hierarchy(object):
self.__codeidxs[c] = i
@property
def codings(self):
"""Return a list of all codings in the hierarchy. """
return list(self.__codings)
def index(self, coding):
"""Return the node ID for the given ``coding``. """
return self.__codeidxs[coding]
......
......@@ -49,21 +49,31 @@ class ICD10Hierarchy(hierarchy.Hierarchy):
def codeToNumeric(code):
"""Converts an ICD10 code into a numeric version. """
# We use the node IDs as defined
# in the ICD10 hierarchy file as
# the numeric version of each
# coding.
hier = hierarchy.getHierarchyFilePath(name='icd10')
hier = hierarchy.loadHierarchyFile(hier)
try:
if code[0].isalpha() and code[1:].isdecimal():
prefix = ord(code[0].lower()) - ord('a') + 11
return int(str(prefix) + str(int(code[1:])))
else:
return np.nan
except Exception:
# hierarchy uses 0-indexing,
# whereas the hierarchy files
# use 1-indexing
return int(hier.index(code) + 1)
except KeyError:
return np.nan
def numericToCode(code):
"""Converts a numeric ICD10 code into its original version. """
code = str(int(code))
prefix = int(code[:2]) + ord('a') - 11
return chr(prefix) + code[2:]
hier = hierarchy.getHierarchyFilePath(name='icd10')
hier = hierarchy.loadHierarchyFile(hier)
try:
return hier.coding(int(code - 1))
except KeyError:
return 'NaN'
def storeCodes(codes):
......
......@@ -24,6 +24,7 @@ import ukbparse.custom as custom
import ukbparse.cleaning_functions as cfns
import ukbparse.importing as importing
import ukbparse.hierarchy as hierarchy
from . import tempdir, gen_test_data, gen_tables, clear_plugins
......@@ -184,12 +185,10 @@ def test_convertICD10Codes(): _test_convertICD10Codes(False)
def test_convertICD10Codes_lowMemory(): _test_convertICD10Codes(True)
def _test_convertICD10Codes(lowMemory):
letters = random.sample(string.ascii_uppercase, 20)
numbers = np.random.randint(1, 1000, 20)
codes = ['{}{}'.format(l, n) for l, n in zip(letters, numbers)] + \
['badcode']
exp = [int(str(ord(l.lower()) - ord('a') + 11) + str(n))
for l, n in zip(letters, numbers)] + [np.nan]
icd10hier = hierarchy.getHierarchyFilePath(name='icd10')
icd10hier = hierarchy.loadHierarchyFile(icd10hier)
codes = list(random.sample(icd10hier.codings, 20)) + ['badcode']
exp = [icd10hier.index(c) + 1 for c in codes[:-1]] + [np.nan]
with tempdir(), mp.Pool(mp.cpu_count()) as pool:
mgr = mp.Manager()
......@@ -198,6 +197,7 @@ def _test_convertICD10Codes(lowMemory):
for i, c in enumerate(codes, 1):
f.write('{}\t{}\n'.format(i, c))
vartable, proctable, cattable, _ = gen_tables([1])
dt, _ = importing.importData('data.txt',
......
......@@ -10,6 +10,8 @@ import textwrap as tw
import string
import random
from unittest import mock
import pytest
import numpy as np
......@@ -22,12 +24,11 @@ from . import tempdir
def test_codeToNumeric():
letters = random.sample(string.ascii_uppercase, 20)
numbers = np.random.randint(1, 1000, 20)
codes = ['{}{}'.format(l, n) for l, n in zip(letters, numbers)] + \
['badcode']
exp = [int(str(ord(l.lower()) - ord('a') + 11) + str(n))
for l, n in zip(letters, numbers)] + [np.nan]
icd10hier = hierarchy.getHierarchyFilePath(name='icd10')
icd10hier = hierarchy.loadHierarchyFile(icd10hier)
codes = list(random.sample(icd10hier.codings, 20)) + ['badcode']
exp = [icd10hier.index(c) + 1 for c in codes[:-1]] + [np.nan]
conv = [icd10.codeToNumeric(c) for c in codes]
......@@ -47,7 +48,8 @@ def test_codeToNumeric():
codes, ncodes = zip(*ncodes)
codes = [c.lower() for c in codes]
assert codes == [icd10.numericToCode(c) for c in ncodes]
assert codes == [icd10.numericToCode(c).lower() for c in ncodes]
def test_store_saveCodes():
......@@ -80,12 +82,14 @@ def test_store_saveCodes():
h = hierarchy.loadHierarchyFile('codings.tsv')
icd10.saveCodes(
'mapping.tsv', h,
fields=['code', 'value', 'description',
'parent_codes', 'parent_descs'])
with mock.patch('ukbparse.hierarchy.getHierarchyFilePath',
return_value='codings.tsv'):
icd10.saveCodes(
'mapping.tsv', h,
fields=['code', 'value', 'description',
'parent_codes', 'parent_descs'])
values = [icd10.codeToNumeric(c) for c in codes]
values = [h.index(c) + 1 for c in codes]
mf = pd.read_csv('mapping.tsv', delimiter='\t', index_col=False)
descs = ['a desc', 'b desc', 'c desc', 'd desc', 'e desc']
......
......@@ -933,11 +933,11 @@ def test_main_icd10():
exp = tw.dedent("""
code\tvalue\tdescription\tparent_descs
a10\t1110\ta desc\t
b20\t1220\tb desc\t[a desc]
c30\t1330\tc desc\t[a desc]
d40\t1440\td desc\t[a desc] [c desc]
e50\t1550\te desc\t[a desc] [b desc]
a10\t5\ta desc\t
b20\t1\tb desc\t[a desc]
c30\t3\tc desc\t[a desc]
d40\t4\td desc\t[a desc] [c desc]
e50\t2\te desc\t[a desc] [b desc]
""").strip()
with open('icd10.tsv', 'wt') as f: f.write(codings)
......@@ -1535,6 +1535,33 @@ def test_main_column_patterns_and_variables():
assert np.all(got.columns == ['col1', '1-0.0', '3-0.0'])
@patch_logging
def test_main_columns_from_file():
data = tw.dedent("""
eid,a,b,c,d1,d2,e
1,10,100,1000,10000,100000,1000000
2,20,200,2000,20000,200000,2000000
3,30,300,3000,30000,300000,3000000
4,40,400,4000,40000,400000,4000000
5,50,500,5000,50000,500000,5000000
""").strip()
with tempdir():
with open('data.txt', 'wt') as f:
f.write(data)
with open('cols.txt', 'wt') as f:
f.write('a\nb\n')
main.main(shlex.split(
'-nb -co cols.txt -co "d*" -co e out.txt data.txt'))
got = pd.read_csv('out.txt', index_col=0, delimiter='\t')
exp = pd.read_csv('data.txt', index_col=0).drop(columns=['c'])
assert got.equals(exp)
@patch_logging
def test_main_variables_and_visits():
......
%% Cell type:markdown id: tags:
![image.png](attachment:image.png)
# `ukbparse`
> Paul McCarthy &lt;paul.mccarthy@ndcn.ox.ac.uk&gt; ([WIN@FMRIB](https://www.win.ox.ac.uk/))
`ukbparse` is a command-line program which you can use to extract data from UK BioBank (and other tabular) data.
You can give `ukbparse` one or more input files (e.g. `.csv`, `.tsv`), and it will merge them together, perform some preprocessing, and produce a single output file.
A large number of rules are built into `ukbparse` which are specific to the UK BioBank data set. But you can control and customise everything that `ukbparse` does to your data, including which rows and columns to extract, and which cleaning/processing steps to perform on each column.
The `ukbparse` source code is available at https://git.fmrib.ox.ac.uk/fsl/ukbparse. You can install `ukbparse` into a Python environment using `pip`:
pip install ukbparse
Get command-line help by typing:
ukbparse -h
*The examples in this notebook assume that you have installed `ukbparse` 0.18.0 or newer.*
*The examples in this notebook assume that you have installed `ukbparse` 0.19.0 or newer.*
%% Cell type:code id: tags:
``` bash
ukbparse -V
```
%% Output
ukbparse 0.18.0
ukbparse 0.19.0
%% Cell type:markdown id: tags:
### Contents
1. [Overview](#Overview)
1. [Import](#1.-Import)
2. [Cleaning](#2.-Cleaning)
3. [Processing](#3.-Processing)
4. [Export](#4.-Export)
2. [Examples](#Examples)
3. [Import examples](#Import-examples)
1. [Selecting variables (columns)](#Selecting-variables-(columns))
1. [Selecting individual variables](#Selecting-individual-variables)
2. [Selecting variable ranges](#Selecting-variable-ranges)
3. [Selecting variables with a file](#Selecting-variables-with-a-file)
4. [Selecting variables from pre-defined categories](#Selecting-variables-from-pre-defined-categories)
2. [Selecting subjects (rows)](#Selecting-subjects-(rows))
1. [Selecting individual subjects](#Selecting-individual-subjects)
2. [Selecting subject ranges](#Selecting-subject-ranges)
3. [Selecting subjects from a file](#Selecting-subjects-from-a-file)
4. [Selecting subjects by variable value](#Selecting-subjects-by-variable-value)
5. [Excluding subjects](#Excluding-subjects)
3. [Selecting visits](#Selecting-visits)
4. [Merging multiple input files](#Merging-multiple-input-files)
1. [Merging by subject](#Merging-by-subject)
2. [Merging by column](#Merging-by-column)
3. [Naive merging](#Merging-by-column)
4. [Cleaning examples](#Cleaning-examples)
1. [NA insertion](#NA-insertion)
2. [Variable-specific cleaning functions](#Variable-specific-cleaning-functions)
3. [Categorical recoding](#Categorical-recoding)
4. [Child value replacement](#Child-value-replacement)
5. [Processing examples](#Processing-examples)
1. [Sparsity check](#Sparsity-check)
2. [Redundancy check](#Redundancy-check)
3. [Categorical binarisation](#Categorical-binarisation)
6. [Custom cleaning, processing and loading - ukbparse plugins](#Custom-cleaning,-processing-and-loading---ukbparse-plugins)
1. [Custom cleaning functions](#Custom-cleaning-functions)
2. [Custom processing functions](#Custom-processing-functions)
3. [Custom file loaders](#Custom-file-loaders)
7. [Miscellaneous topics](#Miscellaneous-topics)
1. [Non-numeric data](#Non-numeric-data)
2. [Dry run](#Dry-run)
3. [Built-in rules](#Built-in-rules)
4. [Using a configuration file](#Using-a-configuration-file)
5. [Reporting unknown variables](#Reporting-unknown-variables)
6. [Low-memory mode](#Low-memory-mode)
%% Cell type:markdown id: tags:
# Overview
`ukbparse` performs the following steps:
## 1. Import
All data files are loaded in, unwanted columns and subjects are dropped, and the data files are merged into a single table (a.k.a. data frame). Multiple files can be merged according to an index column (e.g. subject ID). Or, if the input files contain the same columns/subjects, they can be naively concatenated along rows or columns.
## 2. Cleaning
The following cleaning steps are applied to each column:
1. **NA value replacement:** Specific values for some columns are replaced with NA, for example, variables where a value of `-1` indicates *Do not know*.
2. **Variable-specific cleaning functions:** Certain columns are re-formatted - for example, the [ICD10](https://en.wikipedia.org/wiki/ICD-10) disease codes are converted to integer representations.
3. **Categorical recoding:** Certain categorical columns are re-coded.
4. **Child value replacement:** NA values within some columns which are dependent upon other columns may have values inserted based on the values of their parent columns.
## 3. Processing
During the processing stage, columns may be removed, merged, or expanded into additional columns. For example, a categorical column may be expanded into a set of binary columns, one for each category.
A column may also be removed on the basis of being too sparse, or being redundant with respect to another column.
## 4. Export
The processed data can be saved as a `.csv`, `.tsv`, or `.hdf5` file.
%% Cell type:markdown id: tags:
# Examples
Throughout these examples, we are going to use a few command line options, which you will probably **not** normally want to use:
- `-nb` (short for `--no_builtins`): This tells `ukbparse` not to use the built-in processing rules, which are specifically tailored for UK BioBank data.
- `-ow` (short for `--overwrite`): This tells `ukbparse` not to complain if the output file already exists.
- `-q` (short for `--quiet`): This tells `ukbparse` to be quiet.
Without the `-q` option, `ukbparse` can be quite verbose, which can be annoying, but is very useful when things go wrong. A good strategy is to tell `ukbparse` to send all of its output to a log file with the `--log_file` (or `-lf`) option. For example:
ukbparse --log_file log.txt out.tsv in.tsv
Here's the first example input data set, with UK BioBank-style column names:
%% Cell type:code id: tags:
``` bash
cat data_01.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
1 31 65 10 11 84 22 56 65 90 12
2 56 52 52 42 89 35 3 65 50 67
3 45 84 20 84 93 36 96 62 48 59
4 7 46 37 48 80 20 18 72 37 27
5 8 86 51 68 80 84 11 28 69 10
6 6 29 85 59 7 46 14 60 73 80
7 24 49 41 46 92 23 39 68 7 63
8 80 92 97 30 92 83 98 36 6 23
9 84 59 89 79 16 12 95 73 2 62
10 23 96 67 41 8 20 97 57 59 23
%% Cell type:markdown id: tags:
The numbers in each column name represent:
1. The variable ID
2. The visit, for variables which were collected at multiple points in time.
3. The "instance", for multi-valued variables.
Note that one **variable** is typically associated with several **columns**, although we're keeping things simple for this first example - there is only one visit for each variable, and there are no mulit-valued variables.
%% Cell type:markdown id: tags:
# Import examples
## Selecting variables (columns)
You can specify which variables you want to load in the following ways, using the `--variable` (`-v` for short) and `--category` (`-c` for short) command line options:
* By variable ID
* By variable ranges
* By a text file which contains the IDs you want to keep.
* By pre-defined variable categories
* By column name
### Selecting individual variables
Simply provide the IDs of the variables you want to extract:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -v 1 -v 5 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 5-0.0
1 31 84
2 56 89
3 45 93
4 7 80
5 8 80
6 6 7
7 24 92
8 80 92
9 84 16
10 23 8
%% Cell type:markdown id: tags:
### Selecting variable ranges
The `--variable`/`-v` option accepts MATLAB-style ranges of the form `start:step:stop` (where the `stop` is inclusive):
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -v 1:3:10 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 4-0.0 7-0.0 10-0.0
1 31 11 56 12
2 56 42 3 67
3 45 84 96 59
4 7 48 18 27
5 8 68 11 10
6 6 59 14 80
7 24 46 39 63
8 80 30 98 23
9 84 79 95 62
10 23 41 97 23
%% Cell type:markdown id: tags:
### Selecting variables with a file
If your variables of interest are listed in a plain-text file, you can simply pass that file:
%% Cell type:code id: tags:
``` bash
echo -e "1\n6\n9" > vars.txt
ukbparse -nb -q -ow -v vars.txt out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 6-0.0 9-0.0
1 31 22 90
2 56 35 50
3 45 36 48
4 7 20 37
5 8 84 69
6 6 46 73
7 24 23 7
8 80 83 6
9 84 12 2
10 23 20 59
%% Cell type:markdown id: tags:
### Selecting variables from pre-defined categories
Some UK BioBank-specific categories are baked into `ukbparse`, but you can also define your own categories - you just need to create a `.tsv` file, and pass it to `ukbparse` via the `--category_file` (`-cf` for short):
%% Cell type:code id: tags:
``` bash
echo -e "ID\tCategory\tVariables" > custom_categories.tsv
echo -e "1\tCool variables\t1:5,7" >> custom_categories.tsv
echo -e "2\tUncool variables\t6,8:10" >> custom_categories.tsv
```
%% Cell type:markdown id: tags:
Use the `--category` (`-c` for short) to select categories to output. You can refer to categories by their ID:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cf custom_categories.tsv -c 1 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 7-0.0
1 31 65 10 11 84 56
2 56 52 52 42 89 3
3 45 84 20 84 93 96
4 7 46 37 48 80 18
5 8 86 51 68 80 11
6 6 29 85 59 7 14
7 24 49 41 46 92 39
8 80 92 97 30 92 98
9 84 59 89 79 16 95
10 23 96 67 41 8 97
%% Cell type:markdown id: tags:
Or by name:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cf custom_categories.tsv -c uncool out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 6-0.0 8-0.0 9-0.0 10-0.0
1 22 65 90 12
2 35 65 50 67
3 36 62 48 59
4 20 72 37 27
5 84 28 69 10
6 46 60 73 80
7 23 68 7 63
8 83 36 6 23
9 12 73 2 62
10 20 57 59 23
%% Cell type:markdown id: tags:
### Selecting column names
If you are working with data that has non-UK BioBank style column names, you can use the `--column` (`-co` for short) to select individual columns by their name, rather than the variable with which they are associated. The `--column` option accepts full column names, and also shell-style wildcard patterns:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -co 4-0.0 -co "??-0.0" out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 4-0.0 10-0.0
1 11 12
2 42 67
3 84 59
4 48 27
5 68 10
6 59 80
7 46 63
8 30 23
9 79 62
10 41 23
%% Cell type:markdown id: tags:
## Selecting subjects (rows)
`ukbparse` assumes that the first column in every input file is a subject ID. You can specify which subjects you want to load via the `--subject` (`-s` for short) option. You can specify subjects in the same way that you specified variables above, and also:
* By specifying a conditional expression on variable values - only subjects for which the expression evaluates to true will be imported
* By specifying subjects to exclude
### Selecting individual subjects
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -s 1 -s 3 -s 5 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
1 31 65 10 11 84 22 56 65 90 12
3 45 84 20 84 93 36 96 62 48 59
5 8 86 51 68 80 84 11 28 69 10
%% Cell type:markdown id: tags:
### Selecting subject ranges
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -s 2:2:10 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
2 56 52 52 42 89 35 3 65 50 67
4 7 46 37 48 80 20 18 72 37 27
6 6 29 85 59 7 46 14 60 73 80
8 80 92 97 30 92 83 98 36 6 23
10 23 96 67 41 8 20 97 57 59 23
%% Cell type:markdown id: tags:
### Selecting subjects from a file
%% Cell type:code id: tags:
``` bash
echo -e "5\n6\n7\n8\n9\n10" > subjects.txt
ukbparse -nb -q -ow -s subjects.txt out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
5 8 86 51 68 80 84 11 28 69 10
6 6 29 85 59 7 46 14 60 73 80
7 24 49 41 46 92 23 39 68 7 63
8 80 92 97 30 92 83 98 36 6 23
9 84 59 89 79 16 12 95 73 2 62
10 23 96 67 41 8 20 97 57 59 23
%% Cell type:markdown id: tags:
### Selecting subjects by variable value
The `--subject` option accepts *variable expressions* - you can write an expression performing numerical comparisons on variables (denoted with a leading `v`) and combine these expressions using boolean algebra. Only subjects for which the expression evaluates to true will be imported. For example, to only import subjects where variable 1 is greater than 10, and variable 2 is less than 70, you can type:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -sp -s "v1 > 10 && v2 < 70" out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
1 31 65 10 11 84 22 56 65 90 12
2 56 52 52 42 89 35 3 65 50 67
7 24 49 41 46 92 23 39 68 7 63
9 84 59 89 79 16 12 95 73 2 62
%% Cell type:markdown id: tags:
The following symbols can be used in variable expressions:
| Symbol | Meaning |
|---------------------------|--------------------------|
| `==` | equal to |
| `!=` | not equal to |
| `>` | greater than |
| `>=` | greater than or equal to |
| `<` | less than |
| `<=` | less than or equal to |
| `na` | N/A |
| `&&` | logical and |
| <code>&#x7c;&#x7c;</code> | logical or |
| `~` | logical not |
| `()` | To denote precedence |
### Excluding subjects
The `--exclude` (`-ex` for short) option allows you to exclude subjects - it accepts individual IDs, an ID range, or a file containing IDs. The `--exclude`/`-ex` option takes precedence over the `--subject`/`-s` option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -s 1:8 -ex 5:10 out.tsv data_01.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0 7-0.0 8-0.0 9-0.0 10-0.0
1 31 65 10 11 84 22 56 65 90 12
2 56 52 52 42 89 35 3 65 50 67
3 45 84 20 84 93 36 96 62 48 59
4 7 46 37 48 80 20 18 72 37 27
%% Cell type:markdown id: tags:
## Selecting visits
%% Cell type:markdown id: tags:
Many variables in the UK BioBank data contain observations at multiple points in time, or visits. `ukbparse` allows you to specify which visits you are interested in. Here is an example data set with variables that have data for multiple visits (remember that the second number in the column names denotes the visit):
%% Cell type:code id: tags:
``` bash
cat data_02.tsv
```
%% Output
eid 1-0.0 2-0.0 2-1.0 2-2.0 3-0.0 3-1.0 4-0.0 5-0.0
1 86 76 82 75 34 99 50 5
2 20 25 40 44 30 57 54 44
3 85 2 48 42 23 77 84 27
4 23 30 18 97 44 55 97 20
5 83 45 76 51 18 64 8 33
%% Cell type:markdown id: tags:
We can use the `--visit` (`-vi` for short) option to get just the last visit for each variable:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -vi last out.tsv data_02.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-2.0 3-1.0 4-0.0 5-0.0
1 86 75 99 50 5
2 20 44 57 54 44
3 85 42 77 84 27
4 23 97 55 97 20
5 83 51 64 8 33
%% Cell type:markdown id: tags:
You can also specify which visit you want by its number:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -vi 1 out.tsv data_02.tsv
cat out.tsv
```
%% Output
eid 2-1.0 3-1.0
1 82 99
2 40 57
3 48 77
4 18 55
5 76 64
%% Cell type:markdown id: tags:
## Merging multiple input files
If your data is split across multiple files, you can specify how `ukbparse` should merge them together.
### Merging by subject
For example, let's say we have these two input files (shown side-by-side):
%% Cell type:code id: tags:
``` bash
echo " " | paste data_03.tsv - data_04.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 eid 4-0.0 5-0.0 6-0.0
1 89 47 26 2 19 17 62
2 94 37 70 3 41 12 7
3 63 5 97 4 8 86 9
4 98 97 91 5 7 65 71
5 37 10 11 6 3 23 15
%% Cell type:markdown id: tags:
Note that each file contains different variables, and different, but overlapping, subjects. By default, when you pass these files to `ukbparse`, it will output the intersection of the two files (more formally known as an *inner join*), i.e. subjects which are present in both files:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow out.tsv data_03.tsv data_04.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
2 94 37 70 19 17 62
3 63 5 97 41 12 7
4 98 97 91 8 86 9
5 37 10 11 7 65 71
%% Cell type:markdown id: tags:
If you want to keep all subjects, you can instruct `ukbparse` to output the union (a.k.a. *outer join*) via the `--merge_strategy` (`-ms` for short) option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -ms outer out.tsv data_03.tsv data_04.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
1 89.0 47.0 26.0
2 94.0 37.0 70.0 19.0 17.0 62.0
3 63.0 5.0 97.0 41.0 12.0 7.0
4 98.0 97.0 91.0 8.0 86.0 9.0
5 37.0 10.0 11.0 7.0 65.0 71.0
6 3.0 23.0 15.0
%% Cell type:markdown id: tags:
### Merging by column
Your data may be organised in a different way. For example, these next two files contain different groups of subjects, but overlapping columns:
%% Cell type:code id: tags:
``` bash
echo " " | paste data_05.tsv - data_06.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 eid 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
1 69 80 70 60 42 4 17 36 56 90 12
2 64 15 82 99 67 5 63 16 87 57 63
3 33 67 58 96 26 6 43 19 84 53 63
%% Cell type:markdown id: tags:
In this case, we need to tell `ukbparse` to merge along the row axis, rather than along the column axis. We can do this with the `--merge_axis` (`-ma` for short) option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -ma rows out.tsv data_05.tsv data_06.tsv
cat out.tsv
```
%% Output
eid 2-0.0 3-0.0 4-0.0 5-0.0
1 80 70 60 42
2 15 82 99 67
3 67 58 96 26
4 17 36 56 90
5 63 16 87 57
6 43 19 84 53
%% Cell type:markdown id: tags:
Again, if we want to retain all columns, we can tell `ukbparse` to perform an outer join with the `-ms` option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -ma rows -ms outer out.tsv data_05.tsv data_06.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
1 69.0 80 70 60 42
2 64.0 15 82 99 67
3 33.0 67 58 96 26
4 17 36 56 90 12.0
5 63 16 87 57 63.0
6 43 19 84 53 63.0
%% Cell type:markdown id: tags:
### Naive merging
Finally, your data may be organised such that you simply want to "paste", or concatenate them together, along either rows or columns. For example, your data files might look like this:
%% Cell type:code id: tags:
``` bash
echo " " | paste data_07.tsv - data_08.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 eid 4-0.0 5-0.0 6-0.0
1 30 99 57 1 16 54 60
2 3 6 75 2 43 59 9
3 13 91 36 3 71 73 38
%% Cell type:markdown id: tags:
Here, we have columns for different variables on the same set of subjects, and we just need to concatenate them together horizontally. We do this by using `--merge_strategy naive` (`-ms naive` for short):
%% Cell type:code id: tags:
``` bash
ukbparse -q -ow -ms naive out.tsv data_07.tsv data_08.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 4-0.0 5-0.0 6-0.0
1 30 99 57.0 16.0 54.0 60.0
2 3 6 75.0 43.0 59.0 9.0
3 13 91 36.0 71.0 73.0 38.0
%% Cell type:markdown id: tags:
For files which need to be concatenated vertically, such as these:
%% Cell type:code id: tags:
``` bash
echo " " | paste data_09.tsv - data_10.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0 eid 1-0.0 2-0.0 3-0.0
1 16 34 10 4 40 89 58
2 62 78 16 5 25 75 9
3 72 29 53 6 28 74 57
%% Cell type:markdown id: tags:
We need to tell `ukbparse` which axis to concatenate along, again using the `-ma` option:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -ms naive -ma rows out.tsv data_09.tsv data_10.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0
1 16 34 10
2 62 78 16
3 72 29 53
4 40 89 58
5 25 75 9
6 28 74 57
%% Cell type:markdown id: tags:
# Cleaning examples
Once the data has been imported, a sequence of cleaning steps are applied to each column.
## NA insertion
For some variables it may make sense to discard or ignore certain values. For example, if an individual selects *"Do not know"* to a question such as *"How much milk did you drink yesterday?"*, that answer will be coded with a specific value (e.g. `-1`). It does not make any sense to included these values in most analyses, so `ukbparse` can be used to mark such values as *Not Available (NA)*.
A large number of NA insertion rules, specific to UK BioBank variables, are coded into `ukbparse` (although they will not be used in these examples, as we are using the `--no_builtins`/`-nb` option). You can also specify your own rules via the `--na_values` (`-nv` for short) option.
Let's say we have this data set:
%% Cell type:code id: tags:
``` bash
cat data_11.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0
1 4 1 6
2 2 6 0
3 7 0 -1
4 -1 6 1
5 2 8 4
6 0 2 7
7 -1 0 0
8 7 7 2
9 4 -1 -1
10 8 -1 2
%% Cell type:markdown id: tags:
For variable 1, we want to ignore values of -1, for variable 2 we want to ignore -1 and 0, and for variable 3 we want to ignore 1 and 2:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -nv 1 " -1" -nv 2 " -1,0" -nv 3 "1,2" out.tsv data_11.tsv
cat out.tsv
```
%% Output
eid 1-0.0 2-0.0 3-0.0
1 4.0 1.0 6.0
2 2.0 6.0 0.0
3 7.0 -1.0
4 6.0
5 2.0 8.0 4.0
6 0.0 2.0 7.0
7 0.0
8 7.0 7.0
9 4.0 -1.0
10 8.0
%% Cell type:markdown id: tags:
> The `--na_values` option expects two arguments:
> * The variable ID
> * A comma-separated list of values to replace with NA
%% Cell type:markdown id: tags:
## Variable-specific cleaning functions
A small number of cleaning/preprocessing functions are built into `ukbparse`, which can be applied to specific variables. For example, some variables in the UK BioBank contain ICD10 disease codes, which may be more useful if converted to a numeric format. Imagine that we have some data with ICD10 codes:
%% Cell type:code id: tags:
``` bash
cat data_12.tsv
```
%% Output
eid 1-0.0
1 A481
2 A590
3 B391
4 D596
5 Z980
%% Cell type:markdown id: tags:
We can use the `--clean` (`-cl` for short) option with the built-in `convertICD10Codes` cleaning function to convert the codes to a numeric representation:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cl 1 convertICD10Codes out.tsv data_12.tsv
cat out.tsv
```
%% Output
eid 1-0.0
1 11481
2 11590
3 12391
4 14596
5 36980
1 534
2 596
3 932
4 2159
5 19143
%% Cell type:markdown id: tags:
> The `--clean` option expects two arguments:
> * The variable ID
> * The cleaning function to apply. Some cleaning functions accept arguments - refer to the command-line help for a summary of available functions.
>
> You can define your own cleaning functions by passing them in as a `--plugin_file` (see the [section on custom plugins below](#Custom-cleaning,-processing-and-loading----ukbparse-plugins)).
### Example: flattening hierarchical data
Several variables in the UK Biobank (including the ICD10 disease categorisations) are organised in a hierarchical manner - each value is a child of a more general parent category. The `flattenHierarchical` cleaninng function can be used to replace each value in a data set with the value that corresponds to a parent category. Let's apply this to our example ICD10 data set.
> `ukbparse` needs to know the data coding of hierarchical variables, as it uses this to look up an internal table containing the hierarchy information. So in this example we are creating a dummy variable table file which tells `ukbparse` that the example data uses [data coding 19](https://biobank.ctsu.ox.ac.uk/crystal/coding.cgi?id=19), which is the ICD10 data coding.
%% Cell type:code id: tags:
``` bash
echo -e "ID\tType\tDescription\tDataCoding\tNAValues\tRawLevels\tNewLevels\tParentValues\tChildValues\tClean
1\t\t\t19
" > variables.tsv
ukbparse -nb -q -ow -vf variables.tsv -cl 1 flattenHierarchical out.tsv data_12.tsv
cat out.tsv
```
%% Output
eid 1-0.0
1 Chapter I
2 Chapter I
3 Chapter I
4 Chapter III
5 Chapter XXI
%% Cell type:markdown id: tags:
### Aside: ICD10 mapping file
`ukbparse` has a feature specific to these ICD10 disease categorisations - you can use the `--icd10_map_file` (`-imf` for short) option to tell `ukbparse` to save a file which contains a list of all ICD10 codes that were present in the input data, and the corresponding numerical codes that `ukbparse` generated:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -cl 1 convertICD10Codes -imf icd10_codes.tsv out.tsv data_12.tsv
cat icd10_codes.tsv
```
%% Output
code value description parent_descs
A481 11481 A48.1 Legionnaires' disease [Chapter I Certain infectious and parasitic diseases] [A30-A49 Other bacterial diseases] [A48 Other bacterial diseases, not elsewhere classified]
A590 11590 A59.0 Urogenital trichomoniasis [Chapter I Certain infectious and parasitic diseases] [A50-A64 Infections with a predominantly sexual mode of transmission] [A59 Trichomoniasis]
B391 12391 B39.1 Chronic pulmonary histoplasmosis capsulati [Chapter I Certain infectious and parasitic diseases] [B35-B49 Mycoses] [B39 Histoplasmosis]
D596 14596 D59.6 Haemoglobinuria due to haemolysis from other external causes [Chapter III Diseases of the blood and blood-forming organs and certain disorders involving the immune mechanism] [D55-D59 Haemolytic anaemias] [D59 Acquired haemolytic anaemia]
Z980 36980 Z98.0 Intestinal bypass and anastomosis status [Chapter XXI Factors influencing health status and contact with health services] [Z80-Z99 Persons with potential health hazards related to family and personal history and certain conditions influencing health status] [Z98 Other postsurgical states]
A481 534 A48.1 Legionnaires' disease [Chapter I Certain infectious and parasitic diseases] [A30-A49 Other bacterial diseases] [A48 Other bacterial diseases, not elsewhere classified]
A590 596 A59.0 Urogenital trichomoniasis [Chapter I Certain infectious and parasitic diseases] [A50-A64 Infections with a predominantly sexual mode of transmission] [A59 Trichomoniasis]
B391 932 B39.1 Chronic pulmonary histoplasmosis capsulati [Chapter I Certain infectious and parasitic diseases] [B35-B49 Mycoses] [B39 Histoplasmosis]
D596 2159 D59.6 Haemoglobinuria due to haemolysis from other external causes [Chapter III Diseases of the blood and blood-forming organs and certain disorders involving the immune mechanism] [D55-D59 Haemolytic anaemias] [D59 Acquired haemolytic anaemia]
Z980 19143 Z98.0 Intestinal bypass and anastomosis status [Chapter XXI Factors influencing health status and contact with health services] [Z80-Z99 Persons with potential health hazards related to family and personal history and certain conditions influencing health status] [Z98 Other postsurgical states]
%% Cell type:markdown id: tags:
## Categorical recoding
%% Cell type:markdown id: tags:
You may have some categorical data which is coded in an awkward manner, such as in this example, which encodes the amount of some item that an individual has consumed:
<img src="attachment:image.png" width="100"/>
You can use the `--recoding` (`-re` for short) option to recode data like this into something more useful. For example, given this data:
%% Cell type:code id: tags:
``` bash
cat data_13.tsv
```
%% Output
eid 1-0.0
1 1
2 555
3 444
4 2
5 300
6 444
7 2
8 2
%% Cell type:markdown id: tags:
Let's recode it to be more monotonic:
%% Cell type:code id: tags:
``` bash
ukbparse -nb -q -ow -re 1 "300,444,555" "3,0.25,0.5" out.tsv data_13.tsv
cat out.tsv
```
%% Output
eid 1-0.0
1 1.0
2 0.5
3 0.25
4 2.0
5 3.0
6 0.25
7 2.0
8 2.0
%% Cell type:markdown id: tags:
The `--recoding` option expects three arguments:
* The variable ID
* A comma-separated list of the values to be replaced
* A comma-separated list of the values to replace them with
%% Cell type:markdown id: tags:
## Child value replacement
Imagine that we have these two questions:
* **1**: *Do you currently smoke cigarettes?*