使用尾随行值乘以增长率来填充NA值?

Ada*_*ith 10 r apply plyr na dplyr

NA用前一个值时间填充值的好方法是(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
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我想缺少的值price1来填充4.8*1.02,4.8*1.02^24.8*1.02^3.同样,我想缺少的值price2来填充3.2*1.02,3.2*1.02^2,3.2*1.02^3,和3.2*1.02^4.

我试过这个,但我认为需要设置重复某种方式(apply?):

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

我还没有使用dplyr其他任何东西,所以基础R plyr或类似的东西将被赞赏.

Ben*_*ker 7

假设仅跟踪NAs:

NAgrow <- function(x,growth=0.02) {
    isna <- is.na(x)
    lastval <- tail(x[!isna],1)
    x[isna] <- lastval*(1+growth)^seq(sum(isna))
    return(x)
}
Run Code Online (Sandbox Code Playgroud)

如果有内部NA价值,这会变得有点棘手.

适用于除第一列以外的所有列:

df[-1] <- lapply(df[-1],NAgrow)

##   year   price1   price2
## 1    0 1.100000 1.100000
## 2    1 2.100000 2.100000
## 3    2 3.200000 3.200000
## 4    3 4.800000 3.264000
## 5    4 4.896000 3.329280
## 6    5 4.993920 3.395866
## 7    6 5.093798 3.463783
Run Code Online (Sandbox Code Playgroud)

  • 对于'dplyr`倾斜:`df%>%mutate_each(funs(NAgrow), - year) (4认同)

G. *_*eck 6

使用Reduce以下方法可获得紧凑的基础R解决方案:

growthfun <- function(x, y) if (is.na(y)) (1+growth)*x else y
replace(df, TRUE, lapply(df, Reduce, f = growthfun, acc = TRUE))
Run Code Online (Sandbox Code Playgroud)

赠送:

  year   price1   price2
1    0 1.100000 1.100000
2    1 2.100000 2.100000
3    2 3.200000 3.200000
4    3 4.800000 3.264000
5    4 4.896000 3.329280
6    5 4.993920 3.395866
7    6 5.093798 3.463783
Run Code Online (Sandbox Code Playgroud)

注意:问题中的数据没有非尾随NA值,但如果有一些,那么我们可以使用na.fill动物园来首先用特殊值(如NaN)替换尾随的NA,并查找它而不是NA:

library(zoo)

DF <- as.data.frame(na.fill(df, c(NA, NA, NaN)))
growthfun <- function(x, y) if (is.nan(y)) (1+growth)*x else y
replace(DF, TRUE, lapply(DF, Reduce, f = growthfun, acc = TRUE))
Run Code Online (Sandbox Code Playgroud)


jos*_*ber 5

以下解决方案基于rle在任何位置使用NA并且不依赖于循环来填充缺失值:

NAgrow.rle <- function(x) {
  if (is.na(x[1]))  stop("Can't have NA at beginning")
  r <- rle(is.na(x))
  na.loc <- which(r$values)
  b <- rep(cumsum(r$lengths)[na.loc-1], r$lengths[na.loc])
  x[is.na(x)] <- ave(x[b], b, FUN=function(y) y[1]*(1+growth)^seq_along(y))
  x
}
df[,-1] <- lapply(df[,-1], NAgrow.rle)
#   year   price1   price2
# 1    0 1.100000 1.100000
# 2    1 2.100000 2.100000
# 3    2 3.200000 3.200000
# 4    3 4.800000 3.264000
# 5    4 4.896000 3.329280
# 6    5 4.993920 3.395866
# 7    6 5.093798 3.463783
Run Code Online (Sandbox Code Playgroud)

我将使用for循环放入另外两个解决方案,一个在基础R中,一个在Rcpp中:

NAgrow.for <- function(x) {
  for (i in which(is.na(x))) {
    x[i] <- x[i-1] * (1+growth)
  }
  x
}

library(Rcpp)
cppFunction(
"NumericVector NAgrowRcpp(NumericVector x, double growth) {
  const int n = x.size();
  NumericVector y(x);
  for (int i=1; i < n; ++i) {
    if (R_IsNA(x[i])) {
      y[i] = (1.0 + growth) * y[i-1];
    }
  }
  return y;
}")
Run Code Online (Sandbox Code Playgroud)

基于rle(crimsonjosilber.rle)的解决方案需要大约两倍于基于for循环(josilber.for)的简单解决方案,并且正如预期的那样,Rcpp解决方案是最快的,在大约0.002秒内运行.

set.seed(144)
big.df <- data.frame(ID=1:100000,
                     price1=sample(c(1:10, NA), 100000, replace=TRUE),
                     price2=sample(c(1:10, NA), 100000, replace=TRUE))
crimson <- function(df) apply(df[,-1], 2, function(x){
  if(sum(is.na(x)) == 0){return(x)}
  ## updated with optimized portion from @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)
  lastValIs[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)
})
ggrothendieck <- function(df) {
  growthfun <- function(x, y) if (is.na(y)) (1+growth)*x else y
  lapply(df[,-1], Reduce, f = growthfun, acc = TRUE)
}
josilber.rle <- function(df) lapply(df[,-1], NAgrow.rle)
josilber.for <- function(df) lapply(df[,-1], NAgrow.for)
josilber.rcpp <- function(df) lapply(df[,-1], NAgrowRcpp, growth=growth)
library(microbenchmark)
microbenchmark(crimson(big.df), ggrothendieck(big.df), josilber.rle(big.df), josilber.for(big.df), josilber.rcpp(big.df))
# Unit: milliseconds
#                   expr        min         lq       mean     median         uq         max neval
#        crimson(big.df)  98.447546 131.063713 161.494366 152.477661 183.175840  379.643222   100
#  ggrothendieck(big.df) 437.015693 667.760401 822.530745 817.864707 925.974019 1607.352929   100
#   josilber.rle(big.df)  59.678527 115.220519 132.874030 127.476340 151.665657  262.003756   100
#   josilber.for(big.df)  21.076516  57.479169  73.860913  72.959536  84.846912  178.412591   100
#  josilber.rcpp(big.df)   1.248793   1.894723   2.373469   2.190545   2.697246    5.646878   100
Run Code Online (Sandbox Code Playgroud)


cr1*_*ade 3

看起来dplyr无法处理访问新分配的滞后值。这是一个即使 位于NA列中间也应该有效的解决方案。

df <- apply(
  df, 2, function(x){
    if(sum(is.na(x)) == 0){return(x)}
    ## updated with optimized portion from @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)
  })
Run Code Online (Sandbox Code Playgroud)