使用逻辑运算符在函数中进行子集化

时间:2013-05-24 10:12:33

标签: r function subset

我正在尝试使用逻辑运算符在函数中进行子集化,如下所示:

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

如何设置函数的参数以接受逻辑运算符?

1 个答案:

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