I am trying to populate a new column with five possible values (1:5), based on a set of conditions for different columns, but only seems to pick up the last condition. Something is wrong somewhere but I can't seem to find it.

I've tried ifelse() statements, the generic if.... else if, and regular conditionals without the ifelse() but nothing has worked.

Sample Data: collisons_2016

Sample Data

if (!is.na(collisons_2016$Vehicle_factor_1)==T &&
    !is.na(collisons_2016$Vehicle_factor_2)==T &&
    !is.na(collisons_2016$Vehicle_factor_3)==T &&
    !is.na(collisons_2016$Vehicle_factor_4)==T &&
    !is.na(collisons_2016$Vehicle_factor_5)==T){

  collisons_2016$vehicle_count <- 5

} else if (!is.na(collisons_2016$Vehicle_factor_1)==T&&
           !is.na(collisons_2016$Vehicle_factor_2)==T&&
           !is.na(collisons_2016$Vehicle_factor_3)==T&&
           !is.na(collisons_2016$Vehicle_factor_4)==T&&
           !is.na(collisons_2016$Vehicle_factor_5)==F){

  collisons_2016$vehicle_count <- 4

  } else if (!is.na(collisons_2016$Vehicle_factor_1)==T&&
             !is.na(collisons_2016$Vehicle_factor_2)==T&&
             !is.na(collisons_2016$Vehicle_factor_3)==T&&
             !is.na(collisons_2016$Vehicle_factor_4)==F&&
             !is.na(collisons_2016$Vehicle_factor_5)==F){

    collisons_2016$vehicle_count <-  3

    } else if (!is.na(collisons_2016$Vehicle_factor_1)==T&&
               !is.na(collisons_2016$Vehicle_factor_2)==T&&
               !is.na(collisons_2016$Vehicle_factor_3)==F&&
               !is.na(collisons_2016$Vehicle_factor_4)==F&&
               !is.na(collisons_2016$Vehicle_factor_5)==F){

      collisons_2016$vehicle_count <- 2

    } else if(!is.na(collisons_2016$Vehicle_factor_1)==T&&
              !is.na(collisons_2016$Vehicle_factor_2)==F&&
              !is.na(collisons_2016$Vehicle_factor_3)==F&&
              !is.na(collisons_2016$Vehicle_factor_4)==F&&
              !is.na(collisons_2016$Vehicle_factor_5)==F){

      collisons_2016$vehicle_count <- 1

    } else {

      collisons_2016$vehicle_count <- 0
    }

Current output:

current output

Expected output:

expected output

Thank you in advance for whatever help you can offer!

0 Answers