Search code examples
rinsertrowconditional-statements

Insert rows in R based on a factor condition


I'm attempting to run a rate-of-change calculation on a value column, but cannot due to;

  1. A row is missing after each oil change due to a 'reset'.
  2. My lack of R knowledge in inserting rows based on conditions.

This is my actual dataframe;

Before <- data.frame(
  Engine_ID = as.factor(c(1006,1006,1006,1006,1006,1006,1006)),
  Oil_Change = as.factor(c(1,0,1,1,0,0,0)),
  Value = c(5,6,3,7,9,11,12)
)

and this is what I need;

After <- data.frame(
  Engine_ID = as.factor(c(1006,1006,1006,1006,1006,1006,1006,1006,1006,1006)),
  Oil_Change = as.factor(c(1,NA,0,1,NA,1,NA,0,0,0)),
  Value = c(5,0,6,3,0,7,0,9,11,12)
)

Then I should be able to perform a true rate-of-change on the value column.

To do this, directly after each oil change (Oil_change == 1) I would like to insert a row of zero's.


Solution

  • Before$order <- 1:nrow(Before)
    
    new <- Before[Before$Oil_Change == 1, ]
    new$Oil_Change <- NA
    new$Value <- 0
    
    After <- rbind(Before, new)
    
    After[order(After$order), ][ , -4]
    
       Engine_ID Oil_Change Value
    1       1006          1     5
    11      1006       <NA>     0
    2       1006          0     6
    3       1006          1     3
    31      1006       <NA>     0
    4       1006          1     7
    41      1006       <NA>     0
    5       1006          0     9
    6       1006          0    11
    7       1006          0    12