Skip to content

Instantly share code, notes, and snippets.

@lgatto
Created May 12, 2019 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lgatto/bb378906d2fcaaade21e3ecfbc83fda4 to your computer and use it in GitHub Desktop.
Save lgatto/bb378906d2fcaaade21e3ecfbc83fda4 to your computer and use it in GitHub Desktop.
Generic annotation filter
setClass("CharacterVariableFilter",
contains = "CharacterFilter")
setClass("NumericVariableFilter",
contains = "DoubleFilter")
VariableFilter <- function(field,
value,
condition = "==") {
if (is.numeric(value))
new("NumericVariableFilter",
field = as.character(field),
value = value,
condition = condition)
else if (is.character(value))
new("CharacterVariableFilter",
field = as.character(field),
value = value,
condition = condition)
else
stop("Value type undefined.")
}
gene <- data.frame(foo = 1:10,
symbol = c(letters[1:9], "b"),
seq_name = paste0("chr", c(1, 4, 4, 8, 1, 2, 5, 3, "X", 4)),
bar = paste0(c("a", "b"), 1:10),
stringsAsFactors = FALSE)
doMatch <- function(x, filter) {
do.call(condition(filter), list(x[, field(filter)], value(filter)))
}
doExtract <- function(x, filter) {
x[doMatch(x, filter), ]
}
f1 <- VariableFilter("foo", 5, ">")
f2 <- VariableFilter("bar", "a", "startsWith")
doExtract(gene, f1)
## foo symbol seq_name bar
## 6 6 f chr2 b6
## 7 7 g chr5 a7
## 8 8 h chr3 b8
## 9 9 i chrX a9
## 10 10 b chr4 b10
doExtract(gene, f2)
## foo symbol seq_name bar
## 1 1 a chr1 a1
## 3 3 c chr4 a3
## 5 5 e chr1 a5
## 7 7 g chr5 a7
## 9 9 i chrX a9
@jorainer
Copy link

Only thing is you can't use the filter expressions:

> AnnotationFilter(~ foo > 5)
Error in value[[3L]](cond) : 
  No AnnotationFilter class 'FooFilter' for field 'foo' defined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment