1

Trying to add a new binary column to a dataset that will return a "1" if it meets certain requirements (below) and a "0" if not.

(x == "1") & (width < 1 | width > 5 | height < 1.5 | height > 3.5)

Any idea how to do this??

Adam Bethke
  • 1,028
  • 2
  • 19
  • 35
stu.bacca
  • 11
  • 3
  • 2
    Including a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) in your question will increase your chances of getting an answer. – Samuel Nov 20 '17 at 21:52
  • 2
    Fix what exactly? Do you get an error of some sort? Unexpected output? You should provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output to make it more clear what exactly you are trying to do. – MrFlick Nov 20 '17 at 21:52

1 Answers1

0

a reproducible example is the best way to get an exact answer for your needs. but I would do something like..

library(dplyr)

df2 <- df %>%
       mutate(new_column = ifelse(width > 5, 1, 0))

ifelse works like ifelse(expression, value_if_true, value_if_false) and the expression must resolve to TRUE or FALSE.

This should also work:

df2 <- df %>%
       mutate(new_column = ifelse(((x == "1") & (width < 1 | width > 5 | height < 1.5 | height > 3.5)), 1, 0)
Matt W.
  • 3,692
  • 2
  • 23
  • 46