结合' for'循环使用if-else语句,每个语句中包含多个条件,如果'声明

时间:2017-05-28 16:46:04

标签: r for-loop if-statement contains

我有一个数据帧如下,有4个字符列

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

我想创建第5列,&#34; db&#34;如果该行的所有4列都为空,或者列的值为#34;包含&#34;字符串&#34;效用网格&#34;否则为&#34; db&#34;的值是1。

我编写了下面的代码,它运行但它将db的所有值都设为1,而不管它是否应为0.如果我删除了&#39;或&#39;如果&#39;内有条件。条件。你觉得怎么了?也是我使用的方式&#34;包含&#34;正确?感谢您的帮助!

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
}

1 个答案:

答案 0 :(得分:1)

这是另一种方法:

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