1. 자료의 분포를 히스토그램과 상자 수염 그림(박스 플롯)으로 알아봅니다.
flower <- c(95,67,28,32,65,65,69,33,98,96,76,42,32,38,42,40,40,69,95,92,75,83,76,83,85,62,37,65,63,42,89,65,73,81,49,52,64,76,83,92,93,68,52,79,81,83,59,82,75,82,86,90,44,62,31,36,38,42,39,83,87,56,58,23,35,76,83,85,30,68,69,83,86,43,45,39,83,75,66,83,92,75,89,66,91,27,88,89,93,42,53,69,90,55,66,49,52,83,34,36)
> par(mfrow=c(2,1))
> hist(flower)
> boxplot(flower, horizontal=TRUE)
상자 수염 그림에서 수염은 min, MAX, 상자는 Q1, Q3 그리고 가운데 선은 Q2(median)이며,
수염 밖의 점들은 outlier.
2. 경험적인 규칙(3시그마 규칙 혹은 empirical rule)을 알아봅시다.
> deviation<-c(1,2,3)
> pnorm(deviation)-pnorm(deviation)
68% 95% 99.7% 얻으십니다.
3. 신뢰구간 구할 때 필요한 z/t-score 찾기
conf <- c(0.90, 0.95)
df = 19
z_score <- qnorm(1-(1-conf)/2)
#[1] 1.644854 1.959964
t_score <- qt(1-(1-conf)/2,df)
#[1] 1.729133 2.093024
4. 눈치채셨다시피 확률 분포에 d/p/q/r 두문자를
더하면 각각 distribution, probability density, quantile, random (난수)를
생성/계산하실 수 있습니다.
5. 통계로 진행하는 신뢰구간 계산
5.1 비율
기본 함수를 이용하면 전문적인 방법으로 계산되므로 그냥 함수만드셔서 계산합니다.
x<-8
n<-43#43번 중 8번 스페이드 뽑는 경우
z_interval<-function(x,n,conf){
p_hat <-x/n;
SE_est <- sqrt(p_hat*(1-p_hat)/n);
z_score <- qnorm(1-(1-conf)/2);
margin_of_error <- z_score*SE_est;
conf_interval <- p_hat + margin_of_error*c(-1,1);
return(conf_interval);
}
#(.07,.30) 스페이드 카드 분포율의 95% 신뢰구간
5.2 평균
자료가 있으시다면 6.2로, 없으면 다음 함수를 이용해 보세요.
t_interval<-function(x_bar,Sx,n,conf){
df=n-1;
t_score <- qt(1-(1-conf)/2,df);
margin_of_error <- t_score*Sx/sqrt(n);
conf_interval <- x_bar+margin_of_error*c(-1,1);
return(conf_interval);
}
6. 자료로 구하는 신뢰구간
6.1 비율
자료 정리해서 7.1에서와 같이 통계로 신뢰구간을 구합니다.
#card_n = runif(43);#균등 분포를 따르는 43개의 난수 ... 자료 준비는 댓글을 보세요.
x<-length(which(card=="spade"))#에잇 나옵니다.
n<-length(card)#43
6.2 평균
#t.test(energy_bar_protein, mu=20, alternative=c("two.sided"), conf.level=.95)
t.test(energy_bar_protein, conf.level=.95)
#(20.46771, 22.33229)를 구하였네요.
7. 요약 통계로 진행하는 가설 검정
7.1 비율 (one sample)
#Ho: p = .25
#Ha: p !=.25
alpha = 0.05 #일 때, (x,n) 이 (8,43)인 경우
prop.test(8,43,p=.25,alternative=c("two.sided"),conf.level=1-alpha,correct=FALSE)
#p-value .3328
#신뢰구간이 비범하게 계산되므로 사용시 유의하시기 바랍니다. (참고 3)
7.2 비율 비교(2-proportion sample z-test)
#Ho: p1 = p2
#Ha: p1!= p2
alpha = 0.05 #일 때, (x1,n1)=(306,382), (x2,n2)=(321,382)인 경우
prop.test(x<-c(306,321),n<-c(382,382),alternative=c("two.sided"),conf.level=1-alpha,correct=FALSE)
#p-value는 .1572
7.3 평균
BSDA 라이브러리에 tsum.test 라고 있는데 (왠지 설치가 안 되어서) 그냥 함수를 만들어 씁니다.
ttest1<-function(x_bar,Sx,n,alternative,mu,conf.level){
df=n-1;
t_score<-(x_bar-mu)/(Sx/sqrt(n));
if (alternative=='less'){
p_value <- pt(t_score,df);
} else if (alternative == 'greater'){
p_value <- 1-pt(t_score,df);
}
else {
p_value <- pt(-abs(t_score),df)+(1-pt(abs(t_score),df));
}
#신뢰구간도 함께 계산
#t_interval 함수는 5.2를 보세요.
conf.interval = t_interval(x_bar,Sx,n,conf.level)
#결과값 출력
print(sprintf('t: %f', t_score));#이렇게 해야 출력이 됨
print(sprintf('df: %d', df));
print(sprintf('p-value: %f',p_value));
print(sprintf('%5.1f%% confidence interval: %s',conf.level*100, paste(conf.interval,collapse=' ')))#paste는 숫자를 문자열로 변환시켜 줍니다
}
(예)
> ttest1(9.91,.55,125,alternative<-c('less'),mu<-10,conf.level=.95)
#[1] "t: -1.829510"
#[1] "df: 124"
#[1] "p-value: 0.034863"
7.4 평균 비교
ttest2<-function(mean.x,S.x,n.x,mean.y,S.y,n.y,alternative,conf.level){
SEest = sqrt(S.x^2/n.x+S.y^2/n.y);
df = n.x+n.y-2;#고수의 근사치
#df = (S.x^2/n.x+S.y^2/n.y)^2/(S.x^4/(n.x^2)/(n.x-1)+S.y^4/(n.y^2)/(n.y-1));#이것은 웰치스 t-검정 때 사용되는 df
t_score = (mean.x-mean.y)/SEest;
if (alternative=='less'){
p_value <- pt(t_score,df);
} else if (alternative == 'greater'){
p_value <- 1-pt(t_score,df);
}
else {
p_value <- pt(-abs(t_score),df)+(1-pt(abs(t_score),df));
}
print(sprintf('t: %f', t_score));#이렇게 해야 출력이 됨
print(sprintf('df: %d', df));
print(sprintf('p-value: %f',p_value));
}
8. 자료로 진행하는 가설 검정
8.1 평균
자료준비는 자료 9.1를 보셔요.
t.test(energy_bar_protein, mu=20, alternative=c("two.sided"), conf.level=.95)
8.2 평균 비교
자료준비는 참고 4를 보셔요. 자료 사이에 쉼표 안 넣으셔도 됩니다.
t.test(Value~Group,data=Data, var.equal=FALSE, conf.level=.95)
9. 자료
9.1 비율의 신뢰구간 구할 때 사용해보는 카드 자료 (균등 분포를 따르는 난수를 사용하였습니다.)
card_n <- c(0.036590445,0.454104494,0.415237338,0.546043575,0.391643707,0.142640430,0.563935322,0.634059084,0.491580955,0.680692898,0.249468027,0.365051202,0.611381465,0.737182819,0.355852245,0.856451032,0.603791257,0.240798722,0.790983794,0.743826264,0.766156720,0.697951405,0.538654729,0.001202413,0.170650637,0.722026658,0.337674215,0.932576812,0.142190033,0.546902644,0.675102984,0.586704257,0.244876134,0.804343352,0.551903761,0.423398372,0.688877665,0.003871202,0.980567358,0.879892344,0.910341816,0.521254774,0.037317731)
card<-replicate(43,0)#0을 43번 반복해서 담고 있는 double 벡터 타입
card[which(card_n<.25)]="diamond";#.25보다 작은 수는 다이아몬드
card[intersect(which(card_n>=.25),which(card_n<.50))] = "club"
card[intersect(which(card_n>=.50),which(card_n<.750))] = "heart"
card[which(card_n>=.75)] = "spade"
9.2 한 집단의 평균 t-검정 자료
출처: https://www.jmp.com/en_us/statistics-knowledge-portal/t-test/one-sample-t-test.html
energy_bar_protein <- c(20.70,27.46,22.15,19.85,21.29,24.75,20.75,22.91,25.34,20.33,21.54,21.08,22.14,19.56,21.10,18.04,24.12,19.95,19.72,18.28,16.26,17.46,20.53,22.12,25.06,22.44,19.08,19.88,21.39,22.33,25.79)
참고:
1. R 중급 활용에 필요한 tidyverse 라이브러리의 위엄 https://www.andrew.cmu.edu/user/achoulde/94842/lectures/lecture07/lecture07-94842.html
2. 자료가 정규 분포를 따르는지 확인할 때 qqplot! https://cran.r-project.org/web/packages/distributions3/vignettes/one-sample-z-test.html
3. prop.test로 계산되는 신뢰 구간이 이상하다 https://stats.stackexchange.com/questions/183225/confidence-interval-from-rs-prop-test-differs-from-hand-calculation-and-resul
4. 두 집단 평균이 같은지 다른지 알아보는 t-검정 https://rcompanion.org/rcompanion/d_02.html
댓글 영역
획득법
① NFT 발행
작성한 게시물을 NFT로 발행하면 일주일 동안 사용할 수 있습니다. (최초 1회)
② NFT 구매
다른 이용자의 NFT를 구매하면 한 달 동안 사용할 수 있습니다. (구매 시마다 갱신)
사용법
디시콘에서지갑연결시 바로 사용 가능합니다.