#Task 1:
#Shortly after metric units of length were officially introduced in Australia, each of a group of 44 students was asked to guess, to the nearest metre, the width of the lecture hall in which they were sitting. Another group of 69 students in the same room was asked to guess the width in feet, to the nearest foot. The true width of the hall was 13.1 metres (43.0 feet).
#(1) Check separately if the guesses in metres and guesses in feet follow normal distributions.
#(2) Examine if the two data sets follow the same distribution. If so, then analyze their variances and means from the qq-plot and the sample estimates.
#Create data
metres <- c(8, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 17, 17, 17, 17, 18, 18, 20, 22, 25, 27, 35, 38, 40)
feet <- c(24, 25, 27, 30, 30, 30, 30, 30, 30, 32, 32, 33, 34, 34, 34, 35, 35, 36, 36, 36, 37, 37, 40, 40, 40, 40, 40, 40, 40, 40, 40, 41, 41, 42, 42, 42, 42, 43, 43, 44, 44, 44, 45, 45, 45, 45, 45, 45, 46, 46, 47, 48, 48, 50, 50, 50, 51, 54, 54, 54, 55, 55, 60, 60, 63, 70, 75, 80, 94)
#check if data follows normal dist
stem(metres)
##
## The decimal point is 1 digit(s) to the right of the |
##
## 0 | 89
## 1 | 000000111122333444
## 1 | 55555555666777788
## 2 | 02
## 2 | 57
## 3 |
## 3 | 58
## 4 | 0
stem(feet)
##
## The decimal point is 1 digit(s) to the right of the |
##
## 2 | 457
## 3 | 0000002234445566677
## 4 | 0000000001122223344455555566788
## 5 | 000144455
## 6 | 003
## 7 | 05
## 8 | 0
## 9 | 4
줄기그림만 보아도 자료가 정규분포를 따르고 있지 않고 왼쪽으로 치우쳤다는 것을 확인 할 수 있다. 이를 확인하기 위해 qqplot을 그렸다.
The stem-and-leaf display suggests that the data does not follow a normal distribution - it is skewed to the left. To confirm this, a qqplot was drawn.
#metres vS. normal dist qqplot
x11()
qqnorm(metres, main = 'metres quantile')
qqline(metres, datax = FALSE)
#feet vS. normal dist qqplot
x11()
qqnorm(feet, main = 'feet quantile')
qqline(feet, datax = FALSE)
metres와 feet를 정규분포의 quantile와 그린 확률 plot을 보았을 때 두 개 모두 직선을 이루고 있지 않다는 것을 볼 수 있다. feet는 J-모양을 가지고 있고 meters는 살짝 s-모양을 가지고 있다고 말할 수 있다. 따라서, 두 자료 모두 정규분포를 따로 있다고 하기 어렵다.
The qqplots with [metres vs. normal distribution quantile] and [feet vs. normal distribution quantile] both have a non-straight line. The qqplot for ‘feet’ has a J-shape and the ‘metres’ data has a s-shape line. Thus, both datasets does not follow a normal distribution.
#Examine if the two data sets follow the same distribution. If so, then analyze their variances and means from the qq-plot and the sample estimates.
x11()
par(mfrow=c(1,1))
abline(line(qqplot(feet, metres, xlab = 'metres',ylab = "feet", main = 'Q-Q Plot (metres VS. feet)')))
##alternative lines (trial and error)
#abline(8, 2.2, col = 'dark green')
#abline(8, 2.25, col = 'pink')
#abline(10, 2.15,col = 'gold')
abline(10,2.2,col = 'blue') #for data upto 20 metres
abline(8,2.15,col = 'red')
#mean, variance 계산
mean(metres)
## [1] 16.02273
mean(feet)
## [1] 43.69565
var(metres)
## [1] 51.04598
var(feet)
## [1] 156.1854
2개의 자료가 같은 분포를 따르는지 확인하기 위해 qqplot을 그렸다.
파란색 선은 20 metres까지 있는 점들만 고려하여 그린 선이고, 절편은 10, 기울기는 2.2이다. 20 metres까지는 점들이 제법 강한 선형성을 보이고 있어서 두 자료가 20 metres까지는 비슷한 분포를 가지고 있다고 할 수 있다.
하지만 20 metres와 더 멀어지면서 convex 형태의 곡선으로 이루어진 것을 볼 수 있다. 이러한 점들도 고려하여 best fit 선을 trial and error로 그려봤을 때 절편이 8, 기울기가 2.15인 선이 그려지고 위 그림에서 빨간 선으로 표시되어 있다. 여기서도 20 metres 이후는 점들이 직선과 더 거리가 멀어지는 경향이 있는 것을 확인할 수 있다, 따라서 두 자료가 (20 metres, 55 feet) 까지는 비슷한 분포를 가지고 있으나 그 이후에는 조금씩 다른 분포를 가지고 있다고 할 수 있다.
분산과 평균값은 아래와 같다: 분산: 156.1854 feet, 51.04598 metres 평균: 43.69565 feet, 16.012273 metres
A qqplot was drawn to examine if the two data sets followed the same distribution.
The blue line considers the points up to 20 metres with y-intercept 10 and gradient 2.2. The results show that the two datasets show strong linearity upto 20 metres, thus, up to 20 metres, the two datasets share a similar distribution.
However, past 20 metres, the line becomes convex. Thus, when all the data points are considered, the best fit line (selected through trial-and-error) is the red line with y-intercept 8 and gradient 2.15.
In conclusion, the two data sets have similar distributions until (20 metres, 55 feet), but afterwards, their distributions differ.
The calculated variance and mean are as follows: - Variance: 156.1854 feet, 51.04598 metres - Mean: 43.69565 feet, 16.012273 metres
두 자료의 분포가 어느정도 유사한지 시각적으로 확인하기 위해 histogram과 density graph를 그려보았다.
To visually examine the distribution likeness of the two data sets, a histogram and a density graph were drawn.
#histogram, density graph 그리기
hist(metres)
hist(feet)
plot(density(metres, main = 'Metres'))
## Warning: In density.default(metres, main = "Metres") :
## extra argument 'main' will be disregarded
plot(density(feet, main = 'Feet'))
## Warning: In density.default(feet, main = "Feet") :
## extra argument 'main' will be disregarded
Histogram과 density graph를 보았을 때 두 분포는 상당히 유사한 것으로 보인다. 앞서 그렸던 줄기잎 그림도 참고하면 두 자료의 분포는 상당히 유사하고, qq plot에서 보였던 convex 곡선은 아마도 자료수가 적어서 일어났다고 볼 수 있다. 만약 자료수가 더 많았더라면 두 자료의 분포가 비슷하다는 것을 확인 할 수 있을 것 같다.
The histogram and density graph show that the two data sets follow similar distributions. Considering the stem-and-leaf display previously created, we can conclude that the two data sets have similar distributions. The convex line seen in the qqplot could be explained by the small data size. Thus, if the data size was larger, we could better confirm the level of distribution likeness of the two datasets.
#Task 2:
#In 1960s in the United States of America 16 states owned the retail liquor stores while in 26 the stores were privately owned. (Some are omitted for technical reasons.) The table shows the price in dollars of a fifth of Seagram 7 Crown Whisky in two sets of states in 1961.
#Do the distributions of prices of two group follow the same distribution?
#create data (provided by the instructor)
m=c(4.65, 4.55, 4.11, 4.15, 4.20, 4.55, 3.80, 4.00, 4.19, 4.75, 4.74, 4.50, 4.10, 4.00, 5.05, 4.20)
po=c(4.82, 5.29, 4.89, 4.95, 4.55, 4.90, 5.25, 5.30, 4.29, 4.85, 4.54, 4.75, 4.85, 4.85, 4.50, 4.75, 4.79, 4.85, 4.79, 4.95, 4.95, 4.75, 5.20, 5.10, 4.80, 4.29)
#draw qqplot
abline(line(qqplot(m, po, ylab = 'private ownership states', xlab = 'monopoly states', main = 'Q-Q Plot: private ownership VS. monopoly states')))
#eyeball estimation - trial and error
#abline(1.8, 0.8, col = 'blue')
#abline(1.5, 0.76, col = 'red')
#abline(2, 0.76, col = 'grey')
abline(1.5, 0.76, col = 'red') #most suitable
두 자료에 대한 qq-plot을 그려봤을 때 검정 직선은 line()으로 그려진 것이고 빨간 직선은 trial and error로 가장 적합해 보이는 직선을 그린 것이다. 빨간 직선은 기울기 0.76, 절편 1.5이고 eyeball estimation으로 그렸다.
위 그림을 보았을 때 자료 점들이 직선 주위에 제법 선형적인 형태로 위치되어 있다고 말할 수 있다. 물론 직선과 점들 사이에 거리가 어느정도 있으므로 강한 선형성을 가지고 있다고 할 수 없지만 두 자료가 어느정도 비슷한 분포를 가지고 있다고 해도 될 것 같아. 이 결론을 시각적으로 확인하기 위해 boxplot, histogram, 그리고 줄기그림을 그려 보았다.
The black line is one drawn by R via the line() function, and the red was drawn by trial and error by this writer. The red line has gradient: 0.76, y-intercept: 1.5, drawn by eyeball estimation.
Based on the resulting qq-plot, the data points are located linearly around the drawn lines. Of course, the considerable distance between the data points and the plot line suggests weak linearity, but we could readily conclude that the two data sets have somewhat similar distributions.
To visually confirm this conclusion, a boxplot, histogram, and stem-and-leaf graph were drawn.
#draw stem-and-leaf graph
stem(m)
##
## The decimal point is at the |
##
## 3 | 8
## 4 | 00112222
## 4 | 566778
## 5 | 1
stem(po)
##
## The decimal point is 1 digit(s) to the left of the |
##
## 42 | 99
## 44 | 045
## 46 | 55599
## 48 | 02555590555
## 50 | 0
## 52 | 0590
#draw histogram
hist(m, breaks = 10,xlab="monopoly states",ylim = c(0,10),xlim = c(3,6), main = "Histogram: Monopoly States")
hist(po,breaks = 10, xlab = "privately-owned states",ylim = c(0,10),xlim = c(3,6),main = "Histogram: Privately-owned states" )
#draw boxplot
boxplot(m)
boxplot(po)
줄기그림과 히스토그램을 보았을 때 두 자료의 분표가 유사점이 많다는 것을 알 수 있다. 두 자료 모두 정규분포와 비슷한 형태를 지니고 있는데 데이터 수가 적어서 불확실하다. Privately-owned states (이하 ‘private’)는 양쪽 값들에 비교적 많은 자료가 있다는 점에서 monopoly states (이하 ‘monopoly’)와 다르다.
Boxplot을 통해 private의 중앙값이 monopoly보다 더 크고 분산은 더 작다는 것을 볼 수 있다. Private의 히스토그램을 보았을 때도 상자들이 monopoly보다 더 오른쪽에 위치되어 있는 것을 알 수 있다. 따라서 두 자료의 분포는 비슷할 수 있으나 mean값에는 어느정도 차이가 있다고 말할 수 있겠다. 이 사실을 확인하기 위해 Tukey Mean Difference plot을 그려 보았다.
The stem-and-leaf and histogram show similarities in the distributions of the two data sets. Both distributions are similar to the normal distribution, but uncertainty exists due to small data size. Note that privately-owned states (henceforth ‘Private’) have relatively more data than monopoly states (henceforth ‘Monopoly’).
The boxplot reveals larger median value and smaller variance for ‘Private’. The histogram supports this as the boxes in Private is located towards the right when compared to Monopoly. Therefore, the two data sets may share similar distributions but they have different mean values. To confirm this, a Tukey Mean Difference plot was utilized
#create tukey mean difference plot
library(lattice)
## Warning: 패키지 'lattice'는 R 버전 4.1.3에서 작성되었습니다
qq.x <- qqplot(m, po)$x
qq.y <- qqplot(m, po)$y
plot((qq.x + qq.y)/2, qq.y-qq.x, main = 'Tukey mean difference plot',
ylab = "private ownership - monopoly", xlab = 'mean', ylim = c(-3,3))
abline(0,0)
위 그림에서 볼 수 있듯이 (private – monopoly) 값들이 모두 0 위에 위치 되어 있으므로 private-ownership states에 해당하는 자료들이 더 높은 평균값을 가지고 있다고 볼 수 있다.
따라서, 분포는 비슷한 형태를 가지고 있는 것 같지만 private-ownership 자료의 양쪽 값이 많다는 점 등 다른점 또한 조금씩 존재한다. 두 자료 값들을 비교했을 때 private-ownership tates가 중앙값과 평균이 더 높은 것으로 확인된다.
The plot reveals the difference in mean values of private and monopoly (private - monopoly = data points) are located above the 0 line. Thus, data set for Private has higher mean values.
It can thus be concluded that the two data sets share similar distributions, although differences in data size exist. Moreover, the values of Private data set has higher median and mean values than Monopoly.
#Task 3: #[BLOODFAT.DAT] 혈액 속의 지방과 심장병의 관련성을 연구하기 위한 자료이다. 혈관이 좁아진 사람들(2그룹; 320명)과 그렇지 않은 사람들(1그룹; 51명)의 혈중 지방 분포가 같은지 분석하여라. 그룹의 구분은 빈칸으로 되어있다. 콜레스테롤은 홀수 컬럼, 트라이글리세라이드(triglyceride)(지방의 일종)는 짝수 컬럼이다.
#1그룹과 2그룹의 콜레스테롤의 분포가 같은지 분석한다.
#The data set is from a research that investigates the correlation between blood fat content and cardiovascular diseases.
#Evaluate the distribution of blood fat between patients with narrow blood vessels (group 2) and those with normal blood vessels (group 1).
#call data
data1 <- read.csv("D:\\(NOW) 2022-1\\탐자분\\과제\\Group 1 (bloodfat.dat).csv", header = T)
data2 <- read.csv("D:\\(NOW) 2022-1\\탐자분\\과제\\Group 2 (bloodfat.dat).csv", header = T)
#group 1, 2 categorized by cholesterol, triglyceride
chol1 <- data1$癤풠holesterol
chol2 <- data2$癤풠holesterol
trig1 <- data1$Triglyceride
trig2 <- data2$Triglyceride
The number of data in the two groups was greatly different, and to remedy this, the quantile() function was used to interpolate the large-sized data set using the quantiles from the small-sized data set. A qqplot was then drawn to compare the distributions.
#cholesterol
#draw a qqplot to compare the distributions
x11()
qqplot(sort(chol1), sort(quantile(chol2, probs = ppoints(chol1))), ylab = "group 2 (interpolated)", xlab = "group 1", main= "Cholesterol Levels (Group 1 VS. Group 2)")
abline(0,1)
위 그림을 보면 두 자료가 선형 관계를 가지고 있으나 평균 0, 분산 1인 직선 보다 위에 위치되어 있으므로 중앙값/평균이 다르다는 것을 알 수 있고 두 분포가 완전히 같다고 할 수 없다. 두 자료의 평균값의 차이를 보기 위해 Tukey mean difference plot을 그렸다.
The resulting plot reveals a linear relationship between the two data sets, but since the points are located above the straight line (with mean:0, variance: 1), they have different median/mean values. Thus, the two distributions may not be exactly the same.
A Tukey mean difference plot was drawn to evaluate the difference in the mean values of the two data sets.
#tukey mean difference plot
chol_tot <-qqplot(sort(chol1), sort(quantile(chol2, probs=ppoints(chol1))))
qq.x <- chol_tot$x #Group2
qq.y <- chol_tot$y #Group1
x11()
plot((qq.x+qq.y)/2, qq.x-qq.y, main = "Tukey Mean Difference Plot", ylab = "group 2-group1", xlab = 'mean', ylim = c(10,-40))
abline(0,0)
위에 그림을 보면 (0,0) 직선 위에 평균 점들이 위치되어 있어서 두 그룹의 평균값이 다르고 평균값의 차이가 또한 변동한다는 것을 알 수 있다. 이 현상을 확인하기 위해 boxplot과 histogram을 그려 보았다.
The resulting plot reveals points that are above the straight line (gradient, y-intercept: 0), thus, the difference in the mean values the two data sets is significant and varies. To confirm this observation, a boxplot and histogram were drawn.
#Create histogram, boxplot - for visual comparison of the distributions
#histogram
x11()
hist(sort(chol1),xlim = c(100,400),main = "Group 1 - Cholesterol")
x11()
hist(sort(quantile(chol2, probs=ppoints(chol1))), breaks = 10,xlim = c(100,400),main = "Group 2 - Cholesterol")
#box plot
x11()
boxplot(sort(chol1), main = "Group 1 - Cholesterol")
x11()
boxplot(sort(quantile(chol2, probs=ppoints(chol1))), main = "Group 2 - Cholesterol")
동일한 x축 길이를 사용한 histogram을 그렸을 때 그룹 2 자료가 전체적으로 더 큰 값들을 가지고 있다는 것을 볼 수 있고, boxplot을 보았을 때 group 2의 중앙값이 group 1보다 더 크다는 것을 확인할 수 있다. Histogram을 보았 때 두 자료의 분포는 상당히 유사한 것으로 확인된다.
When comparing the two histograms with same x-axis scales, group 2 data generally have larger values. The boxplots show that the median of group 2 is larger than that of group 1. The variance of the two data sets are similar as shown in the histograms.
#Triglyceride
x11()
qqplot(sort(trig1), sort(quantile(trig2, probs = ppoints(trig1))), ylab = "group 2 (interpolated)", xlab = "group 1", main= "Triglyceride Levels (Group 1 VS. Group 2)")
abline(0,1)
Cholesterol 자료들과 비슷하게 interpolate된 group 2자료와 group1의 자료에 대한 qqplot을 그려 보았다. 평균 0, 기울기 1인 직선위에 점들이 위치되어 있고 선형성을 보이지 않는 것을 보아서 두 자료가 비슷한 분포를 가지고 있다고 하기 어렵다.
이 사실을 확인하기 위해 histogram을 그려보았다.
As it was for the previous data sets, the data for group 2 were interpolated and the resulting data was plotted against group 1 data in a qqplot. The data points are located above the straight line (with mean 0, gradient 1) and show a non-linear pattern. Thus, the two data sets seem to have different distributions.
To confirm this conclusion, a histogram was drawn.
##histogram
hist(sort(trig1),main = "Group 1 - Triglyceride",xlim = c(0,500))
hist(sort(quantile(trig2, probs=ppoints(trig1))), breaks = 10,main = "Group 2 - Triglyceride",xlim = c(0,500))
위 히스토그램을 보았을 때 group 1은 50 – 200 사이에 자료가 몰려 있어 살짝 왼쪽으로 치우쳐 있고 뾰족한 그래프가 나온다. Group 2도 왼쪽으로 치우쳤지만 자료들이 더 넓게 퍼져있는 것을 확인할 수 있다.
따라서, triglyceride자료는 분포가 왼쪽으로 치우쳤다는 점에서 비슷한 모양을 띄고 있지만 오른쪽으로 가면서 group1에는 자료수가 더 적어져서 위 qqplot에서 concave 모양의 고선이 생긴다.
The above histogram shows that group 1 data is clustered in the 50 - 200 range, thus, is slightly left-skewed and has a high peak (= positive kurtosis). Group 2 data also is left-skewed but the data points are more spread out.
Therefore, the two data sets are similar in that they are left-skewed, but the number of available data is less for larger numbers (right end of the x-axis), which leads to a concave curve in the qqplot.
두 자료의 분포가 유사한 것으로 확인되는 cholesterol 자료들의 분포를 확인하기로 했다. Previous finding: the two data sets share a similar distribution - the exact distribution was estimated as follows.
t.chol <- c(chol1, chol2)
t.chol <- sort(t.chol)
i<-1:length(t.chol)
#normal dist
library(MASS)
fitdistr(t.chol, densfu = 'normal') #mean, sd 값 찾기
## mean sd
## 213.315364 42.644083
## ( 2.213970) ( 1.565514)
q.norm.chol <- qnorm((i-0.5)/length(t.chol), mean = 213.315364 , sd = 42.644083)
q.norm.chol <- na.omit(q.norm.chol) #생성된 na값들 제거
plot(q.norm.chol,t.chol, main = "Normal Distribution")
abline(0,1)
#exponential dist
fitdistr(t.chol, densfu = "exponential") #rate 찾기: 결과 = 0.0046878949
## rate
## 0.0046878949
## (0.0002433834)
q.exp.chol <- -log(1-(i-0.5)/length(t.chol)*(0.0046878949 ))
q.exp.chol <- na.omit(q.exp.chol)
plot(q.exp.chol,t.chol, main = 'Exponential Distribution')
#Gamma dist
fitdistr(t.chol, densfu = "gamma") #shape, rate 찾기:
## shape rate
## 25.665328442 0.120316388
## ( 1.870081336) ( 0.008852518)
#결과 = shape: 25.665328442, rate: 0.120316388
겜마 분포의 이론적 모수 (shape, scale)를 계산한 뒤 (fitdistr() 함수 사용) 원래 자료를 사용하여 얻은 shape, scale 모수를 계산했다. 이론적 모수 결과값과 자료로 부터 계산된 값들이 유사하다면 원 자료는 겜마 분포를 따르고 있다고 결론 내릴 수 있겠다.
Calculated the shape and scale parameters from the raw data to compare with fitdistr() results. If these two values are similar, the raw data follows the gamma distribution.
c.mean <- mean(t.chol)
c.var <- var(t.chol)
(c.shape <- c.mean^2/c.var) #24.95483
## [1] 24.95483
(c.scale <- c.mean/c.var) #0.1169856
## [1] 0.1169856
결론: 이론적 모수와 자료로 계산된 모수 값들이 유사하므로 Cholesterol 자료는 겜마 분포를 따른다고 할 수 있다. 위 결론을 확인하기 위해 probability plot을 그려 보았다.
Conclusion drawn: theoretical and raw data parameters (shape, scale) are very similar Thus, the given data probably follows the gamma distribution.
To check this conclusion, we draw a probability plot.
i <- 1:length(t.chol)
x11()
q.gamma.chol <- qgamma((i-0.5)/length(t.chol), shape = c.shape, scale = c.scale)
plot(q.gamma.chol, t.chol, main = 'Gamma distribution')
abline(0,1)
[Probability plot 비교]
3개의 probability plot를 보았을 때 주어진 자료는 정규분포 또는 겜마 분포를 따르고 있다고 할 수 있겠다. 지수 분포 probability plot은 중간부분은 강한 선형관계를 가지고 있으나 끝부분이 곡선을 이루고 있으므로 더 뚜렷한 선형성을 보이는 정규분포나 겜마 분포가 더 적절하다고 생각했다.
정규분포와 겜마분포 위에 평균이 0, 분산이 1인 직선을 그렸을 때 겜마분포 probability plot에는 그려지지 않아 gamma 분포와 주어진 자료는 중앙값과 분산이 완전히 일치하지 않는다고 생각할 수 있겠다.
반면 정규분포 probability plot은 선형성을 보이고 있고 평균 0, 분산 1인 직선 위에 점들이 위치되어 있는 것을 확인 할 수 있다. 양 끝쪽으로 갈수록 직선에서 멀어지는 점들도 있지만 probability plot이 전반적으로 강한 선형성을 보이고 있으므로 cholesterol 자료는 정규분포를 따르고 있다고 결론을 내릴 수 있겠다.
[Comparison between probability plots]
Probability plot results show that the given data follows either normal distribution or gamma distribution. Although a strong linearity is evident in the middle region of the exponential prob plot, the either ends of the graph are curved. Therefore, normal distribution or gamma distribution seem more plausible.
A straight line with mean 0 and variance (gradient) 1 was drawn on each plot, the line failed to appear on the Gamma plot. Thus, the gamma distribution and the given data have different median and variance values.
The normal distribution probability plot shows data points along the straight line with linearity. Some data points towards the either ends of the graph stray away from the line, but overall, the graph shows strong linearity along the given straight line, thus, the Cholesterol data set seems to follow the Normal Distribution.