非标准评估不起作用:h(simpleError(msg, call)) 中的错误
Non standard evaluation does not work: Error in h(simpleError(msg, call))
这是我想做的工作示例。
# 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")
如上面的函数所示,我想以编程方式指定“Species”和“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
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")
这是我想做的工作示例。
# 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")
如上面的函数所示,我想以编程方式指定“Species”和“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
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")