我编写了一段代码,以十分位数计算目标变量的累积值。
我的数据如下所示:
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”是决赛 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.将NA替换为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(out,out1,by='decile') %>%
mutate_each(funs(replace(., is.na(.), 0)), sum_churn:cum_churn)