반응형

문제인식: 자사 제품의 구매율이 다른 앱과 비교하여 낮음을 확인, 해당 배너 광고의 클릭율이 낮음을 밝힘.

 

해결 방법: 분석 위한 데이터가 없기 때문에  A/B 테스트를 통해 분석용 로그를 출력하는 데이터 수집. 이후 A/B 테스트 한 후 배너광고 A B의 클릭률 산출하여 x2 검정 실행

 

R 분석 내용

1. 데이터 읽어 들이기

> setwd("C:/파일/temp/r_temp")

> ab.test.imp <-read.csv('section5-ab_test_imp.csv',header=T,stringsAsFactors = F)

> head(ab.test.imp,2)

log_date app_name  test_name test_case user_id transaction_id

1 2013-10-01  game-01 sales_test         B   36703          25622

2 2013-10-01  game-01 sales_test         A   44339          25623

 

> ab.test.goal <- read.csv('section5-ab_test_goal.csv',header=T,stringsAsFactors = F)

> head(ab.test.goal,2)

log_date app_name  test_name test_case user_id transaction_id

1 2013-10-01  game-01 sales_test         B   15021          25638

2 2013-10-01  game-01 sales_test         B     351          25704

 

2. ab.test.imp ab.test.goal 결합시키기

> ab.test.imp <- merge(ab.test.imp, ab.test.goal, by='transaction_id', all.x=T, suffixes=c('','.g'))

> head(ab.test.imp,2)

 

-> all.x - logical; if TRUE, then extra rows will be added to the output, one for each row in x that has no matching row in y. These rows will have NAs in those columns that are usually filled with values from y. The default is FALSE, so that only rows with data from both x and y are included in the output.

 

3. 클릭했는지 하지 않았는지 나타내는 플래그 작성하기

> ab.test.imp$is.goal <-ifelse(is.na(ab.test.imp$user_id.g),0,1)

-> 항목 user_id.g의 값이 없음(NA)인 경우 0, 그렇지 않을 경우 1 입력

 

4. 클릭률 집계하기

> library(plyr)

> ddply(ab.test.imp,

           .(test_case),

           summarize,

           cvr=sum(is.goal)/length(user_id))

test_case        cvr

1         A 0.08025559

2         B 0.11546015

 

-> cvr = 클릭한 사람의 합계 / 배너광고가 표시된 유저수

    배너광고 A의 클릭률 보다 B가 전반적으로 높다는 것을 통계적으로 알 수 있다.

 

5. 카이제곱 검정

> chisq.test(ab.test.imp$test_case,ab.test.imp$is.goal)

 

Pearson's Chi-squared test with Yates' continuity correction

 

data:  ab.test.imp$test_case and ab.test.imp$is.goal

X-squared = 308.38, df = 1, p-value < 2.2e-16

 

-> p-value가 매주 작으므로 (0.05보다 작음) A B의 차이는 우연히 발생한 것이 아님

 

6. 날짜별,테스트 케이스별로 클릭률 산출하기

> ab.test.imp.summary<- ddply(ab.test.imp,

                                 .(log_date,test_case),

                                 summarize,

                                 imp=length(user_id),

                                 cv=sum(is.goal),

                                 cvr=sum(is.goal)/length(user_id))

> head(ab.test.imp.summary)

log_date test_case  imp  cv        cvr

1 2013-10-01         A 1358  98 0.07216495

2 2013-10-01         B 1391 176 0.12652768

3 2013-10-02         A 1370  88 0.06423358

4 2013-10-02         B 1333 212 0.15903976

5 2013-10-03         A 1213 170 0.14014839

6 2013-10-03         B 1233 185 0.15004055

 

-> imp = 배너 광고가 얼마나 표시되었는지 확인

cv = 클릭한 사람의 합계

cvr = 클릭률

 

7. 테스트 케이스별로 클릭률 산출하기

> ab.test.imp.summary<- ddply(ab.test.imp.summary,

                                 .(test_case),

                                 transform,

                                 cvr.avg=sum(cv/sum(imp)))

> head(ab.test.imp.summary)

log_date test_case  imp  cv        cvr    cvr.avg

1 2013-10-01         A 1358  98 0.07216495 0.08025559

2 2013-10-02         A 1370  88 0.06423358 0.08025559

3 2013-10-03         A 1213 170 0.14014839 0.08025559

4 2013-10-04         A 1521  89 0.05851414 0.08025559

5 2013-10-05         A 1587  56 0.03528670 0.08025559

6 2013-10-06         A 1219 120 0.09844135 0.08025559

 

-> transform: 기존 집계툴에 데이터 추가

   cvr.avg: test_case 별 추가

 

8. 테스트 케이스별 클릭률의 시계열 추이 그래프

> str(ab.test.imp.summary)

'data.frame':          62 obs. of  6 variables:

 $ log_date : chr  "2013-10-01" "2013-10-02" "2013-10-03" "2013-10-04" ...

$ test_case: chr  "A" "A" "A" "A" ...

$ imp      : int  1358 1370 1213 1521 1587 1219 1595 1401 1648 1364 ...

$ cv       : num  98 88 170 89 56 120 194 99 199 114 ...

$ cvr      : num  0.0722 0.0642 0.1401 0.0585 0.0353 ...

$ cvr.avg  : num  0.0803 0.0803 0.0803 0.0803 0.0803 ...

> ab.test.imp.summary$log_date <- as.Date(ab.test.imp.summary$log_date)

 

> library(ggplot2)

> library(scales)

> limits<-c(0,max(ab.test.imp.summary$cvr))

> ggplot(ab.test.imp.summary,aes(x=log_date,y=cvr,

                                    col=test_case,lty=test_case,shape=test_case))+

                                    geom_line(lwd=1)+geom_point(size=4)+geom_line(aes(y=cvr.avg,col=test_case))+

                                    scale_y_continuous(label=percent,limits=limits)

 

-> 배너광고 A의 클릭률 보다 B가 전반적으로 높다는 것을 통계적으로 알 수 있다

 

 

 

##ggplot 그래프 이해하기

> library(ggplot2)

> library(scales)

> ggplot(ab.test.imp.summary,aes(x=log_date,y=cvr,col=test_case,lty=test_case,shape=test_case))

 

 

> ggplot(ab.test.imp.summary,aes(x=log_date,y=cvr,col=test_case,lty=test_case,shape=test_case))+geom_line(lwd=1)

 

 

> ggplot(ab.test.imp.summary,aes(x=log_date,y=cvr,col=test_case,lty=test_case,shape=test_case))+geom_line(lwd=1)+geom_point(size=4)

 

 

> ggplot(ab.test.imp.summary,aes(x=log_date,y=cvr,col=test_case,lty=test_case,shape=test_case))+geom_line(lwd=1)+geom_point(size=4)+geom_line(aes(y=cvr.avg,col=test_case))

 

 

> limits<-c(0,max(ab.test.imp.summary$cvr))

> max(ab.test.imp.summary$cvr)

[1] 0.1712159

> ggplot(ab.test.imp.summary,aes(x=log_date,y=cvr,col=test_case,lty=test_case,shape=test_case))+geom_line(lwd=1)+geom_point(size=4)+geom_line(aes(y=cvr.avg,col=test_case))+ scale_y_continuous(label=percent,limits=limits)

 

 

출처: 비지니스 활용 사레로 배우는 데이터 분석: R (사카마키 류지, 사토 요헤이 지음)

반응형
Posted by 마르띤
,
반응형

4.2.2 독립성 검정

4.3) Goodman Kruskal 6,800명을 대상으로 눈색과 머리색을 조사하여 얻은 자료를 가지고 아래와 같은 관찰표를 얻엇다. 눈색과 머리색에 따라 3X4 분할표를 구성할 눈색이 머리색에 영향을 주는가? , 서로 독립저긴가?

 

B1

B2

B3

B4

A1

1768

807

189

47

2811

A2

946

1387

746

53

3132

A3

115

438

288

16

857

2829

2632

1223

116

6800


   H0 눈색과 머리색은 독립이다

   H1 눈색과 머리색인 서로관련이 있다

 

1) 데이터 입력

> out = matrix(c(1768, 807, 189, 47, 946, 1387, 746, 53, 115, 438, 288, 16), nrow=3, byrow = T)

> dimnames(out) = list (eye=c('e1','e2','e3'),hair=c('h1','h2','h3','h4'))

> out

hair

eye    h1   h2  h3 h4

e1   1768  807 189 47

e2    946 1387 746 53

e3    115  438 288 16

> addmargins(out) #분할표 만들기

hair

eye      h1   h2   h3  h4  Sum

e1     1768  807  189  47 2811

e2      946 1387  746  53 3132

e3      115  438  288  16  857

Sum   2829 2632 1223 116 6800

 

2) 데이터 시각화

> par(mfrow=c(1,2))

> dotchart(out)

> dotchart(t(out))

 

 


> par(mfrow=c(1,1))

> mosaicplot(out)


결과 해석: 눈색과 머릿색이 서로 영향을 주고 있음을 있다

 

 

3) 카이제곱 검정 

> chisq.test(out)

 

Pearson's Chi-squared test

 

data:  out

X-squared = 1073.5, df = 6, p-value < 2.2e-16

결과 해석:

  귀무가설 H0 눈색과 머리색은 독립이다.

  대립가설 H1 눈색과 머리색인 서로관련이 있다.

  p-value 2.2e-16 < 0.001

  의사결정: p-value값이 0.001보다 작으므로 눈색과 머리색이 유의하게 서로 영향을 주고 있음을 알 수 있다.



4) 카이제곱 검정 결과 보기

> names(chisq.test(out))

[1] "statistic" "parameter" "p.value"   "method"    "data.name" "observed"  "expected"  "residuals" "stdres"  

> chisq.test(out)$observed #관찰도수

hair

eye    h1   h2  h3 h4

e1 1768  807 189 47

e2  946 1387 746 53

e3  115  438 288 16

> chisq.test(out)$expected #기대도수

hair

eye         h1        h2       h3       h4

e1 1169.4587 1088.0224 505.5666 47.95235

e2 1303.0041 1212.2682 563.2994 53.42824

e3  356.5372  331.7094 154.1340 14.61941

> chisq.test(out)$residuals #잔차

hair

eye          h1        h2         h3          h4

e1  17.502565 -8.519654 -14.079133 -0.13752858

e2  -9.890092  5.018483   7.697865 -0.05858643

e3 -12.791799  5.836008  10.782543  0.36107650

 

출처: 보건정보데이터 분석(이태림 저)



반응형
Posted by 마르띤
,
반응형

4.2 범주형 자료의 검정

# 4.2) 비타민 c가 감기치료에 효과가 있는지 점검. 대조군(control) 그룹 140명에게는 플라시보를 주고 처리군(treat) 그룹 139명에게는 매일 비타민 c를 투여하였다. 아래 분할표를 가지고 비타민 C가 감기에 효과가 있는지 점검

 

 

감기 걸림

감기 안 걸림

대조군(placebo)

31

109

140

처리군(비타민 C 복용군)

17

122

139

48

231

279

 

H0 복용군과 비복용군의 감기 이환율 같다
H1
복용군과 비복용군의 감기 이환율 다르다

 

1) 자료 입력

> vitamin = matrix(c(31,109,17,122),nrow=2,byrow=T)

> dimnames(vitamin) = list(vitamin=c('ctr','trt'),flu=c('y','n'))

> vitamin

          flu

vitamin  y   n

    ctr 31 109

    trt 17 122

> round(vitamin/sum(vitamin),2)

            flu

vitamin    y    n

    ctr 0.11 0.39

    trt 0.06 0.44

> addmargins(vitamin)

          flu

vitamin  y   n Sum

    ctr 31 109 140

    trt 17 122 139

    Sum 48 231 279

 

2) 데이터 시각화

> par(mfrow=c(1,2))

> dotchart(vitamin)

> dotchart(t(vitamin))


> par(mfrow=c(1,1))

> mosaicplot(vitamin)


결과 해석: 비타민 복용군과 비복용군의 감기 이환율이 동일하지 않음을 알 수 있다.


 

3)카이제곱 검정 실행

#카이검정

> chisq.test(vitamin)

 

Pearson's Chi-squared test with Yates' continuity correction

 

data:  vitamin

X-squared = 4.1407, df = 1, p-value = 0.04186

 

결과해석
대립가설 H0 : 복용군과 비복용군의 감기 이환율 같다

귀무가설 H1 : 복용군과 비복용군의 감기 이환율 다르다

p-value : 0.04186

결정: p-value값이 0.05보다 작으므로 H0를 기각, 비타민 복용군과 비복용군 간 이환율은 다르다.

 

 

관찰도수, 기대도수, 잔차를 보는 법 

#관찰도수

> names(chisq.test(vitamin))

[1] "statistic" "parameter" "p.value"   "method"    "data.name" "observed"  "expected"

[8] "residuals" "stdres"  

> chisq.test(vitamin)$observed

flu

vitamin  y   n

ctr 31 109

trt 17 122


#기대도수

> chisq.test(vitamin)$expected

flu

vitamin        y       n

ctr 24.08602 115.914

trt 23.91398 115.086


#피어슨잔차

> chisq.test(vitamin)$residual

flu

vitamin         y          n

ctr  1.408787 -0.6421849

trt -1.413846  0.6444908


출처: 보건정보데이터 분석(이태림 저)

반응형
Posted by 마르띤
,