lundi 18 mai 2020

Is there a method to do a condition statement in R

I'm trying to add a new column in my data frame based on the condition between two variables. I have two columns visit.x and visit.y. I want to have a new column called a number of visits. so if someone has initial and first visit that means the number of visits is 2 and if there is NA in either visit.x or visit.y that means the number of visits is 1

I used the following code.

df3$number_visit<-"NA"
for(i in 1:nrow(df3)) 
{
  if(df3[i,c("Vistis.x")]   ==  "initial"
     & df3[i,c("Vistis.y")] ==  "first")
  {
    df3$number_visit[i] <- "2"
  }
  if(df3[i,c("Vistis.x")]   ==        "initial"
     & df3[i,c("Vistis.y")] ==      NA)
  {
    df3$number_visit[i] <- "1"
  }
  if(df3[i,c("Vistis.x")]   ==        NA
     & df3[i,c("Vistis.y")] ==      "first")
  {
    df3$number_visit[i] <- "1"
  }
} 

I got this error message

Error in if (df3[i, c("Vistis.x")] == "intial" & df3[i, c("Vistis.y")] ==  : 
  missing value where TRUE/FALSE needed

Can someone help me solve this issue Thank you

Aucun commentaire:

Enregistrer un commentaire