dimanche 28 mai 2017

Combining 'for' loop with if-else statements with multiple conditions inside each 'if' statement

I have a dataframe as follows with 4 character columns

df <- data.frame(2016=c("light", "", "", "", ""), 2017=c("radio", "", "", "", ""), after2017=c("", "Utility grid connection for lighting", "", "", "light"), dkcs=c("", "", "TV", "TV", ""))

I want to create a 5th column, "db" such that it has a value 0 if either all 4 columns are empty for that row or the value of the column "contains" the string "Utility grid", otherwise value of "db" is 1.

I wrote the following code which runs but it is giving all values of db as 1 irrespective of whether it should be 0. The code works correctly if I remove the 'or' condition inside the 'if' condition. What do you think is wrong? Also is the way I am using "contains" correct? I appreciate your help!

for(i in 1:nrow(df)) {

  if(df$2016[i]!= "" | df$2016H2[i]!= "Utility grid.") {
    df$db[i] <- 1
  } else if (df$2017[i]!="" | df$2017[i]!="Utility grid.") {
    df$db[i] <- 1
  } else if (df$after2017[i]!="" | df$after2017[i]!="Utility grid.") {
    df$db[i] <- 1
  } else if (df$dkcs[i]!="" | df$dkcs[i]!="Utility grid.") {
    df$db[i] <- 1
  }
  else df$db[i] <- 0
}

Aucun commentaire:

Enregistrer un commentaire