'독립된 두 표본의 모평균 차이에 대한 추정과 검정'에 해당되는 글 1건

  1. 2015.10.15 R (1) 독립된 두 표본의 모평균 차이에 대한 추정과 검정 : t.test() 11

두개의 모집단에 대한 추정과 검정 (two sample tests)에 대해서 정규분포 가정을 만족하는 경우와 그렇지 않은 경우로 나누어서 알아보겠습니다.

 

 

정규성 가정을 충족하는 경우

 

(1) 독립된 두 표본의 평균 차이에 대한 추정과 검정 : t.test()

     (indepentent two sample t-test)

 

(2) 짝을 이룬 표본에 대한 평균 차이에 대한 추정과 검정 : t.test(paired=TRUE)

     (paired sample t-test)

 

(3) 두 모집단의 모비율 차이에 대한 추정과 검정 : prop.test()

     (independent two population proportions test)

 

 

정규성 가정을 충족하지 못하는 경우, 혹은 분포형태를 모르는 경우

 

(4) 두 모집단의 중심 차이에 대한 비모수 검정 : wilcox.test()

    (non-parametric wilcoxon tests on two indepedent sample)

 

 

먼저, (1) 독립된 두 표본의 평균 차이에 대한 추정과 검정(indepentent two sample t-test)를 R의 t.test() 함수를 이용해 분석해 보겠습니다.

 

예제로 사용할 데이터는 MASS 패키지에 내장된 Cars93 데이터프레임의 가격(Price)과 생산국가(Origin) 입니다. 생산국이 USA vs. non-USA 2개의 group 에 대해서 차 가격(Price)의 평균이 차이가 있는지를 검정해보고, 95% 신뢰구간을 추정해보겠습니다.

 

> # Dataset
> library(MASS)
> str(Cars93)
'data.frame':	93 obs. of  27 variables:
 $ Manufacturer      : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ...
 $ Model             : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ...
 $ Type              : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ...
 $ Min.Price         : num  12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ...
 $ Price             : num  15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ...
 $ Max.Price         : num  18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ...
 $ MPG.city          : int  25 18 20 19 22 22 19 16 19 16 ...
 $ MPG.highway       : int  31 25 26 26 30 31 28 25 27 25 ...
 $ AirBags           : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ...
 $ DriveTrain        : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ...
 $ Cylinders         : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ...
 $ EngineSize        : num  1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ...
 $ Horsepower        : int  140 200 172 172 208 110 170 180 170 200 ...
 $ RPM               : int  6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ...
 $ Rev.per.mile      : int  2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ...
 $ Man.trans.avail   : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ...
 $ Fuel.tank.capacity: num  13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ...
 $ Passengers        : int  5 5 5 6 4 6 6 6 5 6 ...
 $ Length            : int  177 195 180 193 186 189 200 216 198 206 ...
 $ Wheelbase         : int  102 115 102 106 109 105 111 116 108 114 ...
 $ Width             : int  68 71 67 70 69 69 74 78 73 73 ...
 $ Turn.circle       : int  37 38 37 37 39 41 42 45 41 43 ...
 $ Rear.seat.room    : num  26.5 30 28 31 27 28 30.5 30.5 26.5 35 ...
 $ Luggage.room      : int  11 15 14 17 13 16 17 21 14 18 ...
 $ Weight            : int  2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ...
 $ Origin            : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ...
 $ Make              : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ... 

 

 

 

 

(1) 탐색적 분석

 

t-test에 들어가기 전에 탐색적 데이터 분석의 일환으로 R로 Origin별 관측값의 개수를 살펴보고, summary statistics, 박스그림(Box plot)과 Histogram 을 그려보면 아래와 같습니다.  

 

- USA 48개, non-USA 45개 관측치로서 sample size가 작지는 않으므로 t-test에 문제는 없겠습니다.

- summary 통계량(mean), Box plot과 Histogram을 보니 두 집단(USA vs. non-USA)의 가격의 평균에는 큰 차이는 없어보이는군요.

- summary 통계량(Min, Max), Box plot과 Histogram을 보니 두 집단(USA vs. non-USA)의 가격의 분산은 아무래도 차이가 있어보이는데요,

 

이것을 t-검정(t-test)을 통해서 확인해보겠습니다.

 

 

> # frequency distribution table
> table(Cars93$Origin)

    USA non-USA 
     48      45 
> 
> 
> # summary
> with(Cars93, tapply(Price, Origin, summary))
$USA
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   7.40   13.48   16.30   18.57   20.72   40.10 

$`non-USA`
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   8.00   11.60   19.10   20.51   26.70   61.90
> 
> 
> # box plot
> boxplot(Price ~ Origin, # Price by Origin (USA, non-USA)
+         data = Cars93, 
+         main = "Boxplot of Price by Origin",  
+         xlab = "Origin",  # x axis label
+         ylab = "Price") # y axis label
> 

 

> 
> # Histogram
> # install.packages("ggplot2") # only for first user of ggplot2
> library(ggplot2)
> 
> ggplot(Cars93, aes(x=Price)) + 
+   geom_histogram(binwidth=5) + 
+   facet_grid(Origin ~ .) +
+   ggtitle("Histogram of Price by Origin")
 

 

 
 

 

 

 

(2) 두 모집단의 분산 동일성 가정에 대한 검정 : F-test

두 독립 표본의 t-test 에서 두 모집단의 분산 동일성 가정을 만족하는지 여부에 따라 분석 옵션을 달리 주어야 하므로, 먼저 분산 동일성에 대한 F-검정(F-test)을 var.test() 함수를 이용해 해보겠습니다.

 

> # independent two sample variance test : var.test()
> # H0 : variance of price by origin is equal (sigma1^2/sigma2^2  = 1)
> # H1 : variance of price by origin is not equal (sigma1^2/sigma2^2  != 1)
> 
> var.test(Price ~ Origin, data = Cars93)

	F test to compare two variances

data:  Price by Origin
F = 0.47796, num df = 47, denom df = 44, p-value = 0.01387
alternative hypothesis: true ratio of variances is not equal to 1
95 percent confidence interval:
 0.2645004 0.8587304
sample estimates:
ratio of variances 
         0.4779637

 

 

P-value가 0.01387로서 매우 작은 값이 나왔으므로, 유의수준 5% 하에서 두 모집단의 분산이 동일하다는 귀무가설을 기각하고, 분산이 서로 다르다는 대립가설을 채택하게 됩니다.  따라서 아래에 t-test 할 때는 분산 동일성 여부에 대한 옵션에서 FALSE (var.equal = FALSE)를 지정하면 되겠습니다.

 

 


R의 t-test() 함수를 이용하는 방법에는 2가지가 있습니다.  첫번째는 x (numeric vector) ~ factor, data = data.frame 형식으로 사용하는 방법이며, 두번째는 x, y numeric vector 를 이용하는 방법입니다.  아래에 2가지 방법 모두를 순서대로 소개하였으며, 분석 결과는 똑같습니다.


 

(3-1) 두 모집단의 모평균 차이에 대한 추정과 검정 : t-test

        - 방법 1 : x ~ factor, data = data.frame

 

 

> 
> # independent two sample t-test : t-test()
> # H0 : price of USA vs. non-USA is equal
> # H1 : price of USA vs. non-USA is not equal
> 
> ##-- way 1. x ~ factor, data = data.frame
> t.test(Price ~ Origin, 
+        data = Cars93, 
+        alternative = c("two.sided"), # c("two.sided", "less", "greater")
+        var.equal = FALSE, 
+        conf.level = 0.95)

	Welch Two Sample t-test

data:  Price by Origin
t = -0.95449, df = 77.667, p-value = 0.3428
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -5.974255  2.102311
sample estimates:
    mean in group USA mean in group non-USA 
             18.57292              20.50889
 

 

 

 

(3-2) 두 모집단의 모평균 차이에 대한 추정과 검정 : t-test

        - 방법 2 : x, y numeric vectors

 

> 
> ##--- way 2. x, y numeric vectors

>

> # x, y numeric vector indexing > Price_USA <- Cars93[which(Cars93$Origin == c("USA")), c("Price")] > Price_nonUSA <- Cars93[which(Cars93$Origin == c("non-USA")), c("Price")] >

> # t-test() > t.test(Price_USA, Price_nonUSA, + alternative = c("two.sided"), # c("two.sided", "less", "greater") + var.equal = FALSE, + conf.level = 0.95) Welch Two Sample t-test data: Price_USA and Price_nonUSA t = -0.95449, df = 77.667, p-value = 0.3428 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: -5.974255 2.102311 sample estimates: mean of x mean of y 18.57292 20.50889

 

 

P-value 가 0.3428로서 5% 유의수준(significance level) 하에서 양측검정(two-sided test) 결과 'USA와 non-USA의 가격의 모평균에는 차이가 없다'는 귀무가설(H0)을 채택(accept)할 수 있게 되었습니다.

 

그리고, 두 모집단의 모평균 차이에 대한 95% 신뢰구간은 (-5.974255, 2.102311) 로 나왔습니다.

 

많은 도움 되었기를 바랍니다.

 

이번 포스팅이 도움이 되었다면 아래의 '공감 ~♡'를 꾸욱 눌러주세요. ^^

 

 

728x90
반응형
Posted by Rfriend
,