我正在尝试使用逻辑运算符在函数中进行子集化,如下所示:
iris$Species <- as.character(iris$Species)
mySubsetFunction <- function(df, species){
dfSubset <- subset(df, Species==species)
return(dfSubset)
}
mySubsetFunction(iris, species="setosa" | species="virginica")
这会返回错误:
Error: unexpected '=' in "mySubsetFunction(iris, species="setosa" | species="
如何设置函数的参数以接受逻辑运算符?
答案 0 :(得分:4)
你的意思是:
mySubsetFunction <- function(df, species){
dfSubset <- subset(df, Species %in% species)
return(dfSubset)
}
mySubsetFunction(iris, c("setosa", "virginica"))
(但是,在函数内使用subset
时要小心:Why is `[` better than `subset`?)
或直接使用subset
:
subset(iris, Species == "setosa" | Species == "virginica"`)
或
subset(iris, Species %in% c("setosa", "virginica"))