r - Fill NA values with the trailing row value times a growth rate? -


what way populate na values previous value times (1+growth)?

df <- data.frame(year=0:6,                 price1=c(1.1, 2.1, 3.2, 4.8, na, na, na),                  price2=c(1.1, 2.1, 3.2, na, na, na, na)) growth <- .02 

in case, want missing values in price1 filled 4.8*1.02, 4.8*1.02^2, , 4.8*1.02^3. similarly, want missing values in price2 filled 3.2*1.02, 3.2*1.02^2, 3.2*1.02^3, , 3.2*1.02^4.

i've tried this, think needs set repeat somehow (apply?):

library(dplyr)  df %>% mutate(price1=ifelse(is.na(price1),              lag(price1)*(1+growth), price1)) 

i'm not using dplyr else (yet), base r or plyr or similar appreciated.

it looks dplyr can't handle access newly assigned lag values. here solution should work if na's in middle of column.

df <- apply(   df, 2, function(x){     if(sum(is.na(x)) == 0){return(x)}     ## updated optimized portion @josilber     r <- rle(is.na(x))     na.loc <- which(r$values)     b <- rep(cumsum(r$lengths)[na.loc-1], r$lengths[na.loc])     lastvalis <- 1:length(x)     lastvali[is.na(x)] <- b     x[is.na(x)] <-       sapply(which(is.na(x)), function(i){         return(x[lastvalis[i]]*(1 + growth)^(i - lastvalis[i]))       })     return(x)   }) 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -