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

5

我写了一段代码来计算感兴趣的变量按十分位累计值。 我的数据长这样:

 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. 将NAs替换为0 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之后替换NA,因为在此之前我没有得到任何NA(请使用set.seed使其可重现)。 - akrun
是的,抱歉。现在添加了set.seed。 - La Machine Infernale
@LaMachineInfernale 目前所有的 out/out1 都没有缺失值(NAs)。 - akrun
在 cum_churn 中,我有 1, 2, 4, 5, 6, 8, 9 , 10 ,11,没有缺失值。 - akrun
抱歉,akrun,我的第一个版本不够清晰。我现在已经更改了代码,重新表述并提供了实际和预期结果的示例。非常感谢您的关注! - La Machine Infernale
显示剩余2条评论
1个回答

4
我们可以尝试。
 left_join(out,out1,by='decile') %>%
        mutate_each(funs(replace(., is.na(.), 0)), sum_churn:cum_churn)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接