0

Its possible to create a function taking a "logical expression" argument as the subset function does?

For instance, something like this working:

x <- function(d, s)
{
  # ...
  return(subset(d, s))
}

Where d is a data.frame and s is a R logical expression

FerranB
  • 35,683
  • 18
  • 66
  • 85
  • 3
    This is why `subset` is recommended only for use interactively. Basically, don't do this. It just creates headaches. Use standard `[` extraction in functions (`help(Extract)`). – Rich Scriven Sep 09 '16 at 18:31
  • 2
    Take a look at this discussion of `subset` to see why it's tricky: http://adv-r.had.co.nz/Computing-on-the-language.html#subset – MrFlick Sep 09 '16 at 19:29
  • Related: [In R, why is `\[` better than `subset`?](http://stackoverflow.com/questions/9860090/in-r-why-is-better-than-subset) – FerranB Sep 10 '16 at 12:52
  • This may be relevant: http://stackoverflow.com/questions/37326815/why-does-this-simple-function-calling-lm-subset-fail – user20637 Sep 13 '16 at 12:22

2 Answers2

2

One approach is doing it just like subset() (you can see subset() code by getS3method("subset", "data.frame") and my answer is a piece of the code). eval(expr, envir) evaluates the expr argument in the environment specified by envir.

x <- function(d, s) {
  r <- eval(substitute(s), d)
  return(d[r,])
}

a1 <- x(iris, Species == "virginica")
a2 <- x(iris, Species == "virginica" & Sepal.Length > 7)
b <- x(cars, dist > 50)
cuttlefish44
  • 6,586
  • 2
  • 17
  • 34
1

One way would be to use a combination of eval and parse:

x <- function(d, s) {
  return(subset(d, eval(parse(text = s))))
}

high.temp <- x(d = airquality, s = "Temp > 80")
Jeff
  • 435
  • 4
  • 11