Search code examples
rnsephyloseq

Non standard evaluation does not work: Error in h(simpleError(msg, call))


Here is a working example of what I want to do.

# interactive use
subset(iris,Species=="setosa")

# as a function
fn <- function(level,choice) {
  x <- paste0(level,"==","'",choice,"'")
  subset(iris,eval(parse(text=x)))
}
fn("Species","setosa")

As seen in the function above, I want to specify "Species" and "setosa" programmatically and combine that to form an expression. And that works.

But, that doesn't seem to work for another package that I am working with.

#Biocmanager::install("phyloseq")
library(phyloseq)
data(GlobalPatterns)

# interactive use, this works
subset_taxa(GlobalPatterns,Kingdom=='Archaea')

# as a function, this doesn't work
fn <- function(level,choice) {
  x <- paste0(level,"==","'",choice,"'")
  subset_taxa(GlobalPatterns,eval(parse(text=x)))
}
fn(level="Kingdom",choice="Archaea")


Error in h(simpleError(msg, call)) : 
  error in evaluating the argument 'expr' in selecting a method for function 'eval': object 'x' not found 

Does the function behave differently or am I doing something wrong?

R 4.0.2
phyloseq_1.34.0


Solution

  • A solution offered by the authors of the phyloseq package:

    library(phyloseq)
    data(GlobalPatterns)
    
    fn <- function(ps, level, choice) {
            x <- paste0(level,"==","'",choice,"'")
            oldTax <- data.frame(tax_table(ps))
            newTax <- subset(oldTax, eval(parse(text=x)))
            tax_table(ps) <- tax_table(as.matrix(newTax))
            return(ps)
    }
    
    fn(GlobalPatterns, level="Kingdom",choice="Archaea")