PoisonAlien
PoisonAlien

Reputation: 431

filter data.table by a query string

Hi is there any way where I can filter a data.table by a query stored in character ? For. ex.

m <- structure(list(Hugo_Symbol = c("ABCA10", "ABCA4", "ABCC3", "ABCG4", 
"ACTBL2", "ADAMTS12", "ADCY5", "ADSS", "AGXT2", "ANG"), Variant_Classification = c("Splice_Site", 
"Missense_Mutation", "Missense_Mutation", "Missense_Mutation", 
"Missense_Mutation", "Missense_Mutation", "Missense_Mutation", 
"Splice_Site", "Missense_Mutation", "Missense_Mutation"), Variant_Type = c("SNP", 
"SNP", "SNP", "SNP", "SNP", "SNP", "SNP", "SNP", "SNP", "SNP"
), Tumor_Sample_Barcode = c("TCGA.AB.2988", "TCGA.AB.2869", "TCGA.AB.2887", 
"TCGA.AB.2934", "TCGA.AB.2931", "TCGA.AB.2945", "TCGA.AB.2833", 
"TCGA.AB.2912", "TCGA.AB.2822", "TCGA.AB.2988")), .Names = c("Hugo_Symbol", 
"Variant_Classification", "Variant_Type", "Tumor_Sample_Barcode"
), row.names = c(NA, -10L), class = c("data.table", "data.frame"
))

Filtering

#These work fine
m[Variant_Classification %in% 'Splice_Site']
dplyr::filter(.data = m, filter = Variant_Classification %in% 'Splice_Site')

Now what if the query is stored in a character variable.

query <- "Variant_Classification %in% 'Splice_Site'"
#These don't work
dplyr::filter(.data = m, filter = query)
m[,query, with =F]

Is there any way to do so ?

Thanks.

Upvotes: 1

Views: 851

Answers (1)

jogo
jogo

Reputation: 12559

You can do it with:

m[eval(parse(text=query))]

#   Hugo_Symbol Variant_Classification Variant_Type Tumor_Sample_Barcode
#1:      ABCA10            Splice_Site          SNP         TCGA.AB.2988
#2:        ADSS            Splice_Site          SNP         TCGA.AB.2912

The solution for dplyr should be equivalent:

dplyr::filter(.data = m, filter = eval(parse(text=query)))

Upvotes: 7

Related Questions