0

I have made this function that optionally subsets a dataframe:

irisSubset <- function(dataframe, Subset=FALSE){

  df <- dataframe

  if(Subset != FALSE) {
    df <- subset(df, Species %in% Subset)
  }

  df

}


irisSubset(iris, Subset = c("setosa"))
irisSubset(iris, Subset = c("setosa", "versicolor"))
irisSubset(iris)

The function does what I want it to do. However, I realise I have fed a vector to if(), which causes a warning message. Are there any circumstances in which the above function will not work correctly? Is there a way of improving the function and avoiding the warning message?

luciano
  • 13,158
  • 36
  • 90
  • 130
  • 3
    Hi, if(!is.logical(Subset)), or by default Subset could be NULL instead of FALSE and you can check if it is null or not, if(!is.null(Subset)), hth – droopy Jul 12 '13 at 08:31
  • That does indeed work - nice hack. Want to make that an answer? – luciano Jul 12 '13 at 08:34
  • Have you read the [warning](http://stackoverflow.com/q/9860090/1412059) in `?subset`? – Roland Jul 12 '13 at 08:35
  • it seems that my comment was already edited in an answer – droopy Jul 12 '13 at 08:37
  • @droopy - I came up with the same answer simultaneously, but saw yours while posting. I'll delete and you can post yours and get credit. Cheers – Marc in the box Jul 12 '13 at 08:43
  • Aside from the warning pointed out by @Roland about how you should not use `subset` inside functions, how is defining a function so you can write `irisSubset(iris, Subset = c("setosa"))` more useful than just using `subset(iris , Species == "setosa")`? – Simon O'Hanlon Jul 12 '13 at 08:55
  • The code I posted is just some of a long function which requires subset – luciano Jul 12 '13 at 11:24
  • It looks like you expect `Subset` to be either NULL or a collection of names. So, never check it vs. a logical. You might be best served with `if(missing(Subset))` to check for existence, tho' I fail to see how you're going to ensure that the elements of `Subset` are guaranteed to be names of `iris` . I'd recommend you rethink your overall approach to this operation. – Carl Witthoft Jul 12 '13 at 11:52

0 Answers0