-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat_vcf_fields_longer.R
More file actions
93 lines (79 loc) · 2.42 KB
/
Copy pathformat_vcf_fields_longer.R
File metadata and controls
93 lines (79 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env Rscript
# Write stdout and stderr to log file
log <- file(snakemake@log[[1]], open = "wt")
sink(log, type = "message")
sink(log, type = "output")
library(readr)
library(dplyr)
library(tidyr)
library(stringr)
library(purrr)
library(rlang)
library(glue)
library(logger)
empty.to.na <- function(x) {
x[x == ""] <- NA
x
}
# Replace "" values with NA in R filter list
# Snakemake passes filters like: list(ERRORS = c(""))
log_info("Preprocessing data")
filter.include <- lapply(snakemake@params$filter_include, empty.to.na)
filter.exclude <- lapply(snakemake@params$filter_exclude, empty.to.na)
# Process input table
log_info("Applying filters and writing results")
df <- read_tsv(
snakemake@input$tsv,
col_types = cols(
POS = col_integer(),
.default = col_character()
)
) %>%
# Separate <sep>-delimited "...[*]..." columns (e.g. ANN[*].EFFECT)
separate_rows(
contains("[*]"),
sep = snakemake@params$sep,
convert = FALSE
) %>%
# Rename "...[*]..." columns using the provided lookup via Snakemake config
rename(all_of(unlist(snakemake@params$colnames_mapping)))
if (nrow(df) == 0) {
log_info("Writing empty file")
write_tsv(df, snakemake@output$tsv)
} else {
log_info("Processing variants")
df %>%
# Ensure missing values are properly encoded
mutate(across(where(is.character), ~ na_if(.x, "NA"))) %>%
# Separate &-delimited error column (more than one error/warning/info message per row is possible)
mutate(split_errors = strsplit(ERRORS, "&")) %>%
# Keep rows with none of the excluded ERRORS terms, if any
filter(map_lgl(split_errors, ~ !any(. %in% filter.exclude[["ERRORS"]]))) %>%
select(-split_errors) %>%
# Apply filters
filter(
# Keep variants that include required values in each field
!!!map2(
names(filter.include),
filter.include,
~ expr(.data[[!!.x]] %in% !!.y)
),
# Keep variants that exclude required values in each field
!!!map2(
names(filter.exclude),
filter.exclude,
~ expr(!(.data[[!!.x]] %in% !!.y))
)
) %>%
# Keep unique rows
distinct() %>%
mutate(
# Assign variant name using the pattern defined via Snakemake config
VARIANT_NAME = str_glue(snakemake@params$variant_name_pattern),
# Assign sample name
SAMPLE = snakemake@params$sample
) %>%
# Write output file
write_tsv(snakemake@output$tsv)
log_info("Done")
}