r:在计算累积值时将NA替换为0

时间:2016-07-29 18:07:08

标签: r dplyr cumulative-sum

我编写了一段代码,用十分位数计算感兴趣变量的累积值。 我的数据如下:

 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)

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

    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”是决赛桌。当特定十分位数的变量计数为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和0代替NAs 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

1 个答案:

答案 0 :(得分:4)

我们可以尝试

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