【问题标题】:Non standard evaluation does not work: Error in h(simpleError(msg, call))非标准评估不起作用: h(simpleError(msg, call)) 中的错误
【发布时间】:2021-05-26 13:19:40
【问题描述】:

这是我想做的一个工作示例。

# 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")

如上面的函数所示,我想以编程方式指定“物种”和“setosa”,并将它们组合成一个表达式。这行得通。

但是,这似乎不适用于我正在使用的另一个包。

#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 

函数的行为是否不同或我做错了什么?

R 4.0.2
phyloseq_1.34.0

【问题讨论】:

    标签: r nse phyloseq


    【解决方案1】:

    phyloseq 包的作者提供的解决方案:

    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")
    

    【讨论】:

      猜你喜欢
      • 2021-05-30
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      相关资源
      最近更新 更多