Reputation: 680
I'm attempting to run a rate-of-change calculation on a value column, but cannot due to;
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.
Upvotes: 1
Views: 1535
Reputation: 31
provided you understand what you need to do, I think there might be many many ways to do it. The following is a way I could do it according to the way i understood what you need to do. It might be the most inefficient way to accomplish the task:
library(dplyr); library(reshape2)
newChange <- mutate(Before, no = c(1:nrow(Before)),
changeRate = ifelse(as.numeric(as.character(Oil_Change)) > 0, 0,NA)) %>%
melt(., id=c('no', 'Engine_ID')) %>%
mutate(., no = ifelse(variable =='changeRate', no+0.5,no),
variable = ifelse(variable =='changeRate', 'Value', as.character(variable))) %>%
reshape(., direction ='wide', idvar = c('no', 'Engine_ID'), timevar = 'variable') %>%
arrange(no) %>% subset(., !(is.na(value.Oil_Change) & is.na(value.Value)))
names(newChange) <- gsub('value.', '', names(newChange))
newChange$no <- NULL
Upvotes: 0
Reputation: 7347
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
Upvotes: 3
Reputation: 9865
df <- Before
# create a helper column
# which gives number of Oil_Change occurrence before the actual row
df$helper <- cumsum(as.integer(as.character(df$Oil_Change)))
# shift it, so that number changes AFTER the oilchange row
df$helper <- c(0, df$helper[1:(length(df$helper)-1)])
# split data frame by the helper row
dfl <- split(df, df$helper) # look at `dfl` content!
# construct to be added horizontal data row
to.be.added <- t(as.data.frame(c(1006, NA, 0, 0)))
# name it correctly
colnames(to.be.added) <- colnames(df)
rownames(to.be.added) <- 1
# add this list at the end of each sub-data frame
dfl.added <- lapply(dfl, function(df) rbind(df, to.be.added))
# join the sub data frames by rowbinding
res <- Reduce(rbind, dfl.added)
# properly name the rows
rownames(res) <- 1:nrow(res)
# remove helper column
res <- res[, -(ncol(res))]
# voila!
res # remove last line if you don't want it
Engine_ID Oil_Change Value
1 1006 1 5
2 1006 <NA> 0
3 1006 0 6
4 1006 1 3
5 1006 <NA> 0
6 1006 1 7
7 1006 <NA> 0
8 1006 0 9
9 1006 0 11
10 1006 0 12
11 1006 <NA> 0
Upvotes: 0