#輸入sleep資料
data(sleep)
#檢視前6筆資料
head(sleep)
##   extra group ID
## 1   0.7     1  1
## 2  -1.6     1  2
## 3  -0.2     1  3
## 4  -1.2     1  4
## 5  -0.1     1  5
## 6   3.4     1  6
#觀看sleep的結構
str(sleep)
## 'data.frame':    20 obs. of  3 variables:
##  $ extra: num  0.7 -1.6 -0.2 -1.2 -0.1 3.4 3.7 0.8 0 2 ...
##  $ group: Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
##  $ ID   : Factor w/ 10 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
#摘要sleep資料中,control組的部分
summary(sleep[1:10,])
##      extra        group        ID   
##  Min.   :-1.600   1:10   1      :1  
##  1st Qu.:-0.175   2: 0   2      :1  
##  Median : 0.350          3      :1  
##  Mean   : 0.750          4      :1  
##  3rd Qu.: 1.700          5      :1  
##  Max.   : 3.700          6      :1  
##                          (Other):4
#摘要sleep資料中,treatment組的部分
summary(sleep[11:20,])
##      extra        group        ID   
##  Min.   :-0.100   1: 0   1      :1  
##  1st Qu.: 0.875   2:10   2      :1  
##  Median : 1.750          3      :1  
##  Mean   : 2.330          4      :1  
##  3rd Qu.: 4.150          5      :1  
##  Max.   : 5.500          6      :1  
##                          (Other):4
#檢視control組(1)和treatment組(2)睡眠增加的情況
boxplot(formula = extra ~ group, 
 data = sleep,                      
 xlab = "組別",               
 ylab = "增加的睡眠時長",     
 frame.plot = FALSE,             
 boxfill = "grey80",             
 whisklty = 1                    
)

H0:group1的平均數=group2的平均數

H1:group1的平均數≠group2的平均數

t.test(extra ~ group, data = sleep, var.equal = T)
## 
##  Two Sample t-test
## 
## data:  extra by group
## t = -1.8608, df = 18, p-value = 0.07919
## alternative hypothesis: true difference in means between group 1 and group 2 is not equal to 0
## 95 percent confidence interval:
##  -3.363874  0.203874
## sample estimates:
## mean in group 1 mean in group 2 
##            0.75            2.33

結果顯示group1(control)的平均數為0.75,goup2(treatment)的平均數為2.33。t-test的結果中,t值為-1.861,p值=0.0791 > 0.05,在95%信賴區間下,無法拒絕虛無假設。因此說明:control組與treatment組的額外睡眠時間沒有顯著差異。