Dieu94
Dieu94

Reputation: 455

Else if loop not producing the right result?

I am a beginner to R and I am trying to get the following else-if loop working in my R code, but there are errors.

Here is the data frame df:

    ID Var1 Var2
     1  5     A
     2  6     A
     3  17    B
     4  18    A
     5  6     B
     6  20    B

This is the dataframe that I am trying to achieve with this else if statement:

    ID Var1 Var2 Var3
     1  5     A    No
     2  6     A    Maybe
     3  17    B    Maybe
     4  18    A    Yes
     5  6     B    No
     6  20    B    Yes

Var3 is based on the value of Var1 however the thresholds of Yes, Maybe and No differ depending on whether Var2 falls into group A or B.

Here is my code with the conditions written out:

 df$Var3<-rep("x", length(df$ID))

 for (i in c(1:length(df$ID))){

 if(df$Var1[i]<=5 & df$Var2[i]=="A"){
df$Var3[i] =="No"
} else if (df$Var1[i]>5 & df$Var1[i]<10 & df$Var2[i]=="A"){
df$Var3[i]=="Maybe"
} else if (df$Var1[i]>=10 & df$Var2[i]=="A"){
df$Var3[i]=="Yes"
} else if (df$Var1[i]<=10 & df$Var2[i]=="B"){
df$Var3[i] =="No"
} else if (df$Var1[i]>10 & df$Var1[i]<20 & df$Var2[i]=="B"){
df$Var3[i]=="Maybe"
} else if (df$Var1[i]>=20 & df$Var2[i]=="B"){
df$Var3[i]=="Yes"
} else {df$Var3[i]=="error"}
}

The warning messages that I get are these:

Warning messages:
1: In if (df$Var1[i] >= 10 & df$Var2 == "A") { :
the condition has length > 1 and only the first element will be used
2: In if (df$Var1[i] >= 10 & df$Var2 == "A") { :
the condition has length > 1 and only the first element will be used
3: In if (df$Var1[i] >= 10 & df$Var2 == "A") { :
the condition has length > 1 and only the first element will be used
4: In if (df$Var1[i] >= 10 & df$Var2 == "A") { :
the condition has length > 1 and only the first element will be used`

What am I doing wrong?

Upvotes: 0

Views: 61

Answers (1)

jogo
jogo

Reputation: 12559

You can do (use vector operations):

df$Var3 <- "error" ### use the recycling rule

df$Var3[df$Var1<=5 & df$Var2=="A"] <- "No"
df$Var3[df$Var1>5 & df$Var1<10 & df$Var2=="A")] <- "Maybe"
df$Var3[df$Var1>=10 & df$Var2=="A")] <- "Yes"
df$Var3[df$Var1<=10 & df$Var2=="B")] <- "No"
df$Var3[df$Var1>10 & df$Var1<20 & df$Var2=="B")] <- "Maybe"
df$Var3[df$Var1>=20 & df$Var2=="B")] <- "Yes"

Upvotes: 0

Related Questions