user3816784
user3816784

Reputation: 61

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
}

Upvotes: 1

Views: 772

Answers (1)

lukeA
lukeA

Reputation: 54247

Here's an alternative approach:

df <- data.frame(
  `2016`=c("light", "", "", "", "", ""), 
  `2017`=c("radio", "", "", "", "", ""), 
  after2017=c("", "Utility grid connection for lighting", "", "", "light", ""), 
  dkcs=c("", "", "TV", "TV", "", ""), 
  check.names=F)
df$db <- (!grepl("Utility grid|^$", apply(df, 1, paste, collapse="")))+0L
df
#    2016  2017                            after2017 dkcs db
# 1 light radio                                            1
# 2             Utility grid connection for lighting       0
# 3                                                    TV  1
# 4                                                    TV  1
# 5                                            light       1
# 6                                                        0

Upvotes: 1

Related Questions