1

If argument negation is true then the condition should be negated. Is there a more convenient way to write this?

foo <- function (x, type, negation){
  if(type == 1){
    condition <- x > 1
    if(negation){
      condition <- !condition
    }
  }
  if(type == 2){
    condition <- x == 5
    if(negation){
      condition <- !condition
    }
  }
  x[condition]
}

EDIT: example:

x <- 1:10

foo(x, 1, T) # 1
foo(x, 1, F) # 2  3  4  5  6  7  8  9 10
foo(x, 2, T) # 1  2  3  4  6  7  8  9 10
foo(x, 2, F) # 5
W W
  • 769
  • 1
  • 11
  • 26
  • You don't need to write `if(negation)` twice – pogibas Nov 06 '17 at 15:02
  • I have edited my code according to your nice advice. – W W Nov 06 '17 at 15:06
  • What are you trying to achieve with `x[condition]`, what is final result? And what is `x`? Single number? – pogibas Nov 06 '17 at 15:07
  • A vector with elements which fullfill the specific condition (when negation is false) or not fulfill (if negation is true). I wondering is there any constructor in R which can simplify that `ifelse(negation, !condition, condition)` – W W Nov 06 '17 at 15:08
  • Please post example of `x`, `type` and `negation` – pogibas Nov 06 '17 at 15:09
  • Done. I need it to implement behavior of checkboxes for shiny app. The `type` is the id of checkbox and `negation` is a value of checkbox (false/true). Checkbox with `type == 1` has label: exclude values bigger than 1 from dataset. and Checkbox with `type == 2` has label: exclude values equals 5 from dataset. – W W Nov 06 '17 at 15:12
  • @WW how many `type`'s there can be? Only 1 and 2? – pogibas Nov 06 '17 at 15:19
  • plenty of types... and I will be adding more and more in the future. – W W Nov 06 '17 at 15:20

2 Answers2

6

If there will be many types in future, consider using S3 OOP system. If not:

foo <- function(x, type, negation) {
  condition <- switch(
    type,
    `1` = x > 1,
    `2` = x == 5
  )

  x[xor(negation, condition)]
}
echasnovski
  • 1,161
  • 8
  • 13
2

(after @PoGibas comment):

foo <- function (x, type, negation){
  if(type == 1){
    condition <- x > 1
  }
  if(type == 2){
    condition <- x == 5
  }
  if(negation){
    condition <- !condition
  }
  x[condition]
}

any other ideas to improve it more?

W W
  • 769
  • 1
  • 11
  • 26
  • Leaving a comment here since you deleted your last question too quickly. The answer to your problem can be found [here](https://stackoverflow.com/q/40391272/324364). – joran Nov 07 '17 at 21:27
  • thx, I just found the soultion that it is better to leave `ggplot()` arguments empty and put'em into the specific `geom_` – W W Nov 07 '17 at 21:29
  • Yes, that is one of three possible solutions, as outlined at the answer I linked to, although which is best depends on the situation and your preference. – joran Nov 07 '17 at 21:32