Trying to add a column but getting a condition has length >1 error

后端 未结 1 1933
我寻月下人不归
我寻月下人不归 2021-01-22 10:48

for (i in 1:nrow(y)){
  if (y$first_completed_date == NA) {
    y$comp[i]<-1
  }
  else {
    y$comp[i]<-0
  }
}

the condition has length > 1 an

相关标签:
1条回答
  • 2021-01-22 11:22

    is.na can be used for creating a logical expression for NA elements instead of ==. Also, warning is because we are using if/else and not ifelse as if/else is not vectorized. The straightforward option would be to create the logical expression with is.na and coerce that to binary with as.integer so that TRUE -> 1 and FALSE ->0

    y$comp <- as.integer(is.na(y$first_completed_date)) 
    
    0 讨论(0)
提交回复
热议问题