Skip to content

Instantly share code, notes, and snippets.

@beneon
Created December 8, 2022 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beneon/4b1b61303b086af9b41c6ec5df2a14f5 to your computer and use it in GitHub Desktop.
Save beneon/4b1b61303b086af9b41c6ec5df2a14f5 to your computer and use it in GitHub Desktop.
code for [video(BV1TP4y1h75Z)](https://www.bilibili.com/video/BV1TP4y1h75Z/?vd_source=8579eab403ebaedc61b3bfd1c6d9fa59), demonstrating the rationale for direct standardization
x1 = c(0,1500,500,500)
y1 = c(0,975,470,475)
x2 = c(0,500,1500,500)
y2 = c(0,315,1365,460)
df_patients = data.frame(
patient_1 = x1,
cure_1 = y1,
patient_2 = x2,
cure_2 = y2
)[2:length(df_patients),]
rate_calculate = function(x,y){
x = x[2:length(x)]
y = y[2:length(y)]
return(y/x)
}
sum_vector = function(x){
return (c(0,sum(x)))
}
library(ggplot2)
ggplot(data=NULL)+
geom_line(aes(x=cumsum(x1),y=cumsum(y1)),color='black')+
geom_point(aes(x=cumsum(x1),y=cumsum(y1)),color='black',size=2)+
geom_line(aes(x=cumsum(x2),y=cumsum(y2)),color='red')+
geom_point(aes(x=cumsum(x2),y=cumsum(y2)),color='red',size=2)+
geom_line(aes(x=sum_vector(x1),y=sum_vector(y1)),color='black')+
geom_line(aes(x=sum_vector(x2),y=sum_vector(y2)),color='red')+
xlab('patients')+
ylab('cures')
rate1 = rate_calculate(x1,y1)
rate2 = rate_calculate(x2,y2)
df = data.frame(segment=1:3,rate1=rate1,rate2=rate2)
ggplot(data=df)+geom_col(aes(y=rate1,x=segment))+geom_col(aes(y=rate2,x=segment),fill='red')
x_common = c(0,1000,1500,300)
y1_standard = x_common*c(0,rate1)
y2_standard = x_common*c(0,rate2)
ggplot(data=NULL)+
geom_line(aes(x=cumsum(x_common),y=cumsum(y1_standard)),color='black')+
geom_point(aes(x=cumsum(x_common),y=cumsum(y1_standard)),color='black')+
geom_line(aes(x=cumsum(x_common),y=cumsum(y2_standard)),color='red')+
geom_point(aes(x=cumsum(x_common),y=cumsum(y2_standard)),color='red')+
geom_line(aes(x=sum_vector(x_common),y=sum_vector(y1_standard)),color='black')+
geom_line(aes(x=sum_vector(x_common),y=sum_vector(y2_standard)),color='red')+
xlab('patients')+
ylab('cures')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment