rstringevaluate

Evaluate string expression (R, Seurat)


I'm trying to evaluate a string expression in the subset() function of the R Seurat package. https://satijalab.org/seurat/articles/essential_commands.html

For example, instead of

subset(x = pbmc, subset = MS4A1 > 3)

I want to do

string.to.evaluate = "MS4A1 > 3"
subset(x = pbmc, subset = string.to.evaluate)

I know eval(parse()) can sometimes be used to evaluate string expressions, but this fails since MS4A1 is a rowname inside pbmc. Is there a way to do this?

Edit: For clarity, "MS4A1" is a rowname of the "counts" slot inside the S4 SeuratObject pbmc. In the Seurat package, there's a subset method for cleanly accessing and filtering SeuratObjects, and I'd like to call it dynamically by passing it strings.


Solution

  • You could do the following:

    string.to.evaluate = "MS4A1 > 3"
    subset(x = pbmc, !!str2lang(string.to.evaluate))
    

    Example:

    data(pbmc_small, package = "SeuratObject")
    string.to.evaluate = "nCount_RNA>202"
    subset(x = pbmc_small, !!str2lang(string.to.evaluate))
    
    An object of class Seurat 
    230 features across 36 samples within 1 assay 
    Active assay: RNA (230 features, 20 variable features)
     2 dimensional reductions calculated: pca, tsne