0

I'm trying to use a logical operator to subset in a function as follows:

iris$Species <- as.character(iris$Species)

mySubsetFunction <- function(df, species){
  dfSubset <- subset(df, Species==species)
  return(dfSubset)
}

mySubsetFunction(iris, species="setosa" | species="virginica")

This returns an error:

Error: unexpected '=' in "mySubsetFunction(iris, species="setosa" | species="

How can I set up the arguments of the function to accept logical operators?

luciano
  • 13,158
  • 36
  • 90
  • 130

1 Answers1

4

You meant to either do:

mySubsetFunction <- function(df, species){
    dfSubset <- subset(df, Species %in% species)
    return(dfSubset)
}

mySubsetFunction(iris, c("setosa", "virginica"))

(However, use caution when using subset inside functions: Why is `[` better than `subset`?)

Or use subset directly:

subset(iris, Species == "setosa" | Species == "virginica"`)

or

subset(iris, Species %in% c("setosa", "virginica"))
Community
  • 1
  • 1
Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235