lundi 29 août 2016

if statement inside a for statement runs only once in R

I have a dataframe which contains the following text:

df$Position 

[1] "START"  "MIDDLE" "MIDDLE" "START"  "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START"  "START"  "START"  "MIDDLE" "MIDDLE" "MIDDLE" "START" 

[22] "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" [43] "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE"

I would like to replace the "MIDDLE" text before the previous "START" text with "END" to mark the correct position.

So i am basically iterating through the positions in the frame and if the condition is met then replace the text.

for(i in 2:i)
{    
# iterate through the frame
if (df$Position[i]=="START" && df$Position[i-1]=="MIDDLE")

{
df$Position[i-1] <- "END"
}
}

This appears to work once only. I end up with the following output:

[1] "START"  "MIDDLE" "END"    "START"  "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START"  "START"  "START"  "MIDDLE" "MIDDLE" "MIDDLE" "START" 

[22] "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "START" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" [43] "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE" "MIDDLE"

I'm wondering what i am doing wrong here and if there is a better approach (maybe a custom function??) to complete this task.

Regards Jonathan

Aucun commentaire:

Enregistrer un commentaire