2

I'm trying to build a subset function in R that will accept dataframes as well as column names and running into issues using the lazyeval approach outlined here. Here's my code:

iris_fun <- function(df, selection_var, selection_input){

  temp <- subset(df, ~.data[[.env$selection_var]] == .env$selection_input)

  return(temp)

}

When I attempt to call this with:

iris_fun(iris, "Species", "setosa")

I get an error message:

Error in subset.data.frame(df, ~.data[[.env$selection_var]] == selection_input) : 'Subset' must be logical

Advice appreciated!

c. garrett
  • 69
  • 2
  • 4
  • Your question doesn't make any sense. What are you trying to do, really? – Hong Ooi Mar 04 '16 at 19:42
  • @HongOoi, I'm trying to build a function that will subset a dataframe based on a given criteria (which will actually come from another dataframe). For now, I'm trying to get the first part to work -- subsetting based on a variable and value that will be inputs to the function (along with a dataframe). – c. garrett Mar 04 '16 at 19:45
  • 1
    in that example, hadley has redefined `subset` so it is no longer `base::subset` – rawr Mar 04 '16 at 21:18
  • See: http://stackoverflow.com/questions/11880906/pass-subset-argument-through-a-function-to-subset – fishtank Mar 04 '16 at 22:47
  • @rawr you are 100% right -- thank you! My wheels were spending way too much time spinning. – c. garrett Mar 04 '16 at 22:49
  • It actually succeeds with version 0.1.10.9000 loaded. – IRTFM Mar 05 '16 at 00:23

1 Answers1

0

The R subset function is not designed for programming. This will do what you ask with none of the non-standard eval confusion:

iris_fun <- function(df, selection_var, selection_input){
                     df[ df[[selection_var]] == selection_input , ]}

(Unfortunately that article on "lazyeval" doesn't seem to be consistent with the package v 0.1.10. There's no f_eval or f_interp, so you cannot define the (lazy):subset-function. Need the devel-version.)

IRTFM
  • 258,963
  • 21
  • 364
  • 487