-1

I need to update the object values == "fix" so that they update to the value of the proceeding value in the same variable. My problem is that when the previous value was also == "fix" it doesn't see the updated value (because clearly it hasn't updated yet, why not?). I'm afraid I don't have the vocabulary to ask the proper question, so here's what it looks like.

So if this is my data frame(df):

row     x
1       a
2       b
3       fix 
4       fix 
5       fix 
6       b
7       a
8       fix 
9       fix 

I run my code:

df$x2 <- ifelse( df$x=="fix",lag(df$x2),df$x) 

I get this:

row     x       x2 
1       a       a
2       b       b
3       fix     b
4       fix     fix
5       fix     fix
6       b       b
7       a       a
8       fix     a
9       fix     fix

But what I want is this:

row     x       x2
1       a       a
2       b       b
3       fix     b
4       fix     b
5       fix     b
6       b       b
7       a       a
8       fix     a
9       fix     a

Any help would be appreciated (including on how to better frame the question and/or title of my question).

MrFlick
  • 195,160
  • 17
  • 277
  • 295
AJost
  • 1
  • 1
  • I've tried running the above code in a loop function, but clearly didn't do it correctly as I get the error "assignments are forbidden." – AJost Mar 04 '16 at 20:23
  • If you think of "fix" values as missing, you are essentially asking for a "last observation carried forward" (LOCF) replacement. See this question for relevant answers: http://stackoverflow.com/questions/2776135/last-observation-carried-forward-in-a-data-frame – MrFlick Mar 04 '16 at 20:36
  • 1
    From the linked answer `zoo::na.locf(replace(df$x, df$x=="fix", NA))` – Pierre L Mar 04 '16 at 20:48

1 Answers1

0

Maybe not the fastest one (because I use for loop), but working:

df2 <- data.frame(x=c("a","b", "fix", "fix", "fix", "b", "a", "fix", "fix"), stringsAsFactors = FALSE)
#df2 <- cbind(df2, data.frame(x2=character(nrow(df2)), stringsAsFactors = FALSE))

for(i in 1:nrow(df2))
{
   if(df2$x[i]=="fix")
   {
       df2$x2[i] <- df2$x2[i-1]   
   }
   else
   {
      df2$x2[i] <- df2$x[i]   
   }
}
df2
Pierre L
  • 28,203
  • 6
  • 47
  • 69
bartoszukm
  • 693
  • 3
  • 10