r:计算累加值时用0代替NA

r: replace NA with 0 when calculating cumulative values

我写了一段代码来按十分位数计算感兴趣变量的累积值。 我的数据如下所示:

 library(dplyr)
actual=c(1,1,1,0,0,1,1,0,0,1)
prob=c(0.8,0.8,0.2,0.1,0.6,0.7,0.8,0.9,0.7,0.9)
n=1:10
for_chart=data.frame(actual,prob,n)
for_chart=for_chart[with(for_chart, order(-prob)),]
for_chart$decile <- cut(n, breaks = quantile(n, probs = seq(0, 1, 0.1)), 
                        labels = 1:10, include.lowest = TRUE)

这是构建 table 并计算累积值的代码。

    out <- for_chart%>%
  group_by(decile)%>%
  summarise(sum=n())%>%
  mutate(cum=cumsum(sum))
out1 <-for_chart%>% 
  filter(actual==1)%>%
  group_by(decile)%>%
  summarise(sum_churn=n())%>%
  mutate(cum_churn=cumsum(sum_churn))
final_out <- left_join(out,out1,by='decile')

"out"给出n的累计计数。 "out1" 提供感兴趣变量的累积值,在本例中为 "cum_churn"。 "final_out" 是最后的 table。当特定十分位数的变量计数为 0 时,代码将放置 NA。像这样:

    final_out
    decile   sum   cum sum_churn cum_churn
       (fctr) (int) (int)     (int)     (int)
    1       1     1     1        NA        NA
    2       2     1     2         1         1
    3       3     1     3         1         2
    4       4     1     4         1         3
    5       5     1     5         1         4
    6       6     1     6         1         5
    7       7     1     7        NA        NA
    8       8     1     8        NA        NA
    9       9     1     9         1         6
    10     10     1    10        NA        NA

我希望我的代码能够: 1. 用 0 和替换 NA 2. 在累计计数中包含 0

为了清楚起见,最终输出应该是这样的:

  decile   sum   cum sum_churn cum_churn
   (fctr) (int) (int)     (int)     (int)
1       1     1     1         0         0
2       2     1     2         1         1
3       3     1     3         1         2
4       4     1     4         1         3
5       5     1     5         1         4
6       6     1     6         1         5
7       7     1     7         0         5
8       8     1     8         0         5
9       9     1     9         1         6
10     10     1    10         0         6

我们可以试试

 left_join(out,out1,by='decile') %>%
        mutate_each(funs(replace(., is.na(.), 0)), sum_churn:cum_churn)