Home > Enterprise >  If statement with three true conditions
If statement with three true conditions

Time:12-09

This is my data:

Year1 <- c(2015,2013,2012,2018)
Year2 <- c(2017,2015,2014,2020)
my_data <- data.frame(Year1, Year2)

I need an if statement that returns 1 when year 1 equals 2015 OR 2016 AND year 2 is greater than 2016. Currently, my code looks like this:

    my_data <- my_data %>%
mutate(Y_2016=ifelse(my_data$Year1==2015|2016 & my_data$Year1>2016,1,0))

But this does not work and only seems to check the condition if Year 2 is greater than 2016, since it returns 1 even for the last row when Year 1 is 2018 and Year 2 is 2020.

Thank you for your help!

CodePudding user response:

  1. Instead of my_data$Year1==2015|2016, use %in% like my_data$Year1 %in% c(2015,2016).

  2. Typo in my_data$Year1>2016

  3. As you using dplyr you do not need to specify every variable with $ like my_data$...

    my_data%>%
      mutate(Y_2016=ifelse(Year1 %in% c(2015,2016) & Year2>2016,1,0))

      Year1 Year2 Y_2016
    1  2015  2017      1
    2  2013  2015      0
    3  2012  2014      0
    4  2018  2020      0

  • Related