K-medoids clustering (R PAM) Start

BioinformaticsAndMe






K-medoids clustering (PAM; Partitioning Around Medoids)

: 이전에 소개된 K-means clustering은 평균을 이용하기에 이상치(outlier)에 민감함

: PAM(Partitioning Around Medoids, 1987)는 평균 대신 대표주자(medoid)를 선택하고, 더 좋은 군집을 만드는 대표주자가 있으면 대체

: PAM은 K-means보다 강건한 방법(robust method)

: PAM은 소규모 자료 적용에는 유리하지만, 대규모 자료 적용에는 불안정(non-scalable)




K-medoids clustering 과정

1) 패키지 설치

install.packages(“cluster”) library(cluster)

2) pam 함수 적용

pam.result <- pam(iris, 3)

3) table 함수로 배치된 클러스터 확인

table(pam.result$clustering, iris$Species)

    setosa versicolor virginica
  1     50          0         0
  2      0          3        49
  3      0         47         1

4) 한 화면에 클러스터링 결과가 모두 출력

par(mfrow=c(1,2)) plot(pam.result) par(mfrow=c(1,1))

clusterplot

: iris 데이터가 3개의 클러스터로 나뉨

: 분홍선은 클러스터간의 거리


Silhouette plot of pam

: iris 데이터의 실루엣(silhouette)

: 군집 1에는 50개 데이터를 포함 (0.80은 클러스터링 설명력)

#1.00 에 가까울수록 데이터들이 적합하게 클러스터링

#음수값은 데이터가 잘못된 클러스터에 속함







#Reference

1) https://rstudio-pubs-static.s3.amazonaws.com/249084_09c0daf4ceb24212a81ceddca97ba1ea.html

2) http://ropatics.com/data-mining/r-and-data-mining/RDM-Clustering.html

3) https://slidesplayer.org/slide/15150112/

4) https://blog.naver.com/asus1984/120065317344

5) https://win100.tistory.com/167





K-medoids clustering (R PAM) End

BioinformaticsAndMe

'R' 카테고리의 다른 글

[R Shiny] 샤이니 소개  (0) 2019.10.06
Hierarchical clustering (R 계층적 군집화)  (0) 2019.10.04
K-means clustering (R 군집분석)  (0) 2019.09.24
if, else, else if, ifelse (R 조건문)  (0) 2019.09.16
while, for (R 반복문)  (0) 2019.09.16

K-means clustering (R 군집분석) Start

BioinformaticsAndMe






K-means clustering

: K-평균 클러스터링은 주어진 데이터를 K개의 클러스터로 묶는 알고리즘

: 각 클러스터와 거리 차이의 분산을 최소화하는 방식으로 작동

: 자율 학습의 일종

: Label이 없는 입력 데이터에 Label을 표지하는 역할을 수행



K-means clustering 과정
1) 새로운 변수 설정
iris2 <- iris 

2) 5번째 컬럼 제거                   
iris2$Species <- NULL 
  
3) kmeans 알고리즘으로 클러스터링 3개 생성
kmeans.result <- kmeans(iris2, 3)            


4) 실제 클러스터링 결과 점검을 위해, 테이블을 생성하여 비교
table(iris$Species, kmeans.result$cluster)              


5) 시각화
plot(iris2[c("Sepal.Length", "Sepal.Width")], col = kmeans.result$cluster, pch=15)            

6) 각 클러스터 중심 그리기 (centers : 각 클러스터별로 컬럼의 평균값을 나타낸 것)
points(kmeans.result$centers[,c("Sepal.Length", "Sepal.Width")], col= 1:3, pch=8, cex=4)


 


#Reference

1) http://pypr.sourceforge.net/kmeans.html

2) http://ropatics.com/data-mining/r-and-data-mining/RDM-Clustering.html






K-means clustering (R 군집분석) End

BioinformaticsAndMe

'R' 카테고리의 다른 글

Hierarchical clustering (R 계층적 군집화)  (0) 2019.10.04
K-medoids clustering (R PAM)  (0) 2019.09.30
if, else, else if, ifelse (R 조건문)  (0) 2019.09.16
while, for (R 반복문)  (0) 2019.09.16
R, as.Date (날짜 변환)  (0) 2019.06.03

if, else, else if, ifelse (R 조건문) Start

BioinformaticsAndMe






R의 조건문


1. if, else (조건 1개 지정)


if (condition 1){

  조건 1 참이면 실행되는 코드}

else{

  조건 1 거짓이면 실행되는 코드}

}




2. else if (조건 추가 지정)


if (condition 1){

  조건 1 참이면 실행되는 코드}

else if (condition 2){

  조건 1 거짓이고, 조건 2 참이면 실행되는 코드}

else{

  조건 1, 2가 모두 거짓이면 실행되는 코드

}




3. ifelse


ifelse(a, b, z)
a가 참이면 b를 출력하고, 거짓이면 z를 출력함

a <- c(11,12)
b <- ifelse(a%%10==1, "apple", "banana")
b

[1] "apple"  "banana"






#조건문 기호 의미

'요소' %in% '범주' --> '요소'가 '범주'에 있는가?

'May' %in% month.name

5 %in% 10:20


비교 조건에 사용되는 연산자

== : 같다

!= : 같지 않다

>= : 크거나 같다

> : 크다

<= : 작거나 같다

<: 작다


여러 가지 조건 지정하기

! : ~가 아니다 (부정)

& : AND (교집합)

| : OR (합집합)








if, else, else if, ifelse (R 조건문) End

BioinformaticsAndMe

'R' 카테고리의 다른 글

K-medoids clustering (R PAM)  (0) 2019.09.30
K-means clustering (R 군집분석)  (0) 2019.09.24
while, for (R 반복문)  (0) 2019.09.16
R, as.Date (날짜 변환)  (0) 2019.06.03
pathview (패스웨이 분석)  (2) 2019.05.22

while, for (R 반복문) Start

BioinformaticsAndMe






R의 반복문


1. while


i <- 0

while (i < 10) {

print (i)

i <- i + 1

}


[1] 0

[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

[1] 6

[1] 7

[1] 8

[1] 9




2. for


for(m in month.name){

print(m)

}


[1] "January"

[1] "February"

[1] "March"

[1] "April"

[1] "May"

[1] "June"

[1] "July"

[1] "August"

[1] "September"

[1] "October"

[1] "November"

[1] "December"





#반복문과 조건문을 이용한 예제

letters벡터와 for, if문을 이용해서 c('a','e','i','o','u')인 경우에만 출력하는 코드


test <- c('a','e','i','o','u')

for(i in test){

  if(i %in% letters ){

    print(i)}

}


[1] "a"

[1] "e"

[1] "i"

[1] "o"

[1] "u"







while, for (R 반복문) End

BioinformaticsAndMe

'R' 카테고리의 다른 글

K-means clustering (R 군집분석)  (0) 2019.09.24
if, else, else if, ifelse (R 조건문)  (0) 2019.09.16
R, as.Date (날짜 변환)  (0) 2019.06.03
pathview (패스웨이 분석)  (2) 2019.05.22
R, 파일 입출력 (FILE I/O)  (0) 2018.09.11

R, as.Date (날짜 변환) Start.

BioinformaticsAndMe






as.Date

: 날짜 type으로 conversion



#실습데이터

> weight <- c(65.4, 55, 380, 72.2, 51, NA)

> height <- c(170, 155, NA, 173, 161, 166)

> gender <- c("M", "F","M","M","F","F")

> testDate <- c("2013/09/01", "2013/09/01", "2013/09/05", "2013/09/14", "2013/10/11", "2013/10/26")

> patients <- data.frame( weight = weight, height=height, gender=gender, testDate=testDate)




#환자 데이터 날짜를 실제 date 형태로 계산하기

> patients

  weight height gender   testDate

1   65.4    170      M 2013/09/01

2   55.0    155      F 2013/09/01

3  380.0     NA      M 2013/09/05

4   72.2    173      M 2013/09/14

5   51.0    161      F 2013/10/11

6     NA    166      F 2013/10/26


> patients$testDate <- as.Date(testDate)

> patients

  weight height gender   testDate
1   65.4    170      M 2013-09-01
2   55.0    155      F 2013-09-01
3  380.0     NA      M 2013-09-05
4   72.2    173      M 2013-09-14
5   51.0    161      F 2013-10-11
6     NA    166      F 2013-10-26





R, as.Date (날짜 변환) End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

if, else, else if, ifelse (R 조건문)  (0) 2019.09.16
while, for (R 반복문)  (0) 2019.09.16
pathview (패스웨이 분석)  (2) 2019.05.22
R, 파일 입출력 (FILE I/O)  (0) 2018.09.11
R, T-test (R, T검정)  (0) 2018.08.29

pathview (pathway 분석) Start.

BioinformaticsAndMe



요즘은 프로그램을 굳이 배우지 않더라도 쉽게 pathway 분석을 할 수 있다.

오늘 소개하는 R 패키지인 'pathview'는 어렵지 않게

expression data(ex. RNA-seq 데이터)를 시각화할 수 있다.

예제 파일을 다운받아 따라해보자.

RNA_seq_example.txt



https://bioconductor.org/packages/release/bioc/html/pathview.html




1. 패키지 설치, 실습 데이터 로딩

# 패키지 설치
source("https://bioconductor.org/biocLite.R")
biocLite("pathview")
biocLite("gage")
biocLite("gageData")
library(pathview)
library(gage)
library(gageData)

# 실습 데이터 로딩
setwd("C:/Users/Documents")
res = read.delim("RNA_seq_example.txt", header=T, row.names = 1)
dim(res) ; View(res)



2. KEGG pathway 데이터 로딩

# Human KEGG pathway data
data(kegg.sets.hs)
str(kegg.sets.hs)

# Only signaling and metabolism만 담음
data(sigmet.idx.hs)
kegg.sets.hs = kegg.sets.hs[sigmet.idx.hs]
head(kegg.sets.hs, 3)



3. 실습데이터 정리

dim(res)
foldchanges = res$log2FoldChange

# entrez gene 혹은 ensembl gene 으로 이름 붙이기
# entrez gene 으로 이름 붙이기
names(foldchanges) = res$entrez
# ensembl gene 로 이름 붙이기
names(foldchanges) = rownames(res)

head(foldchanges)
head(kegg.sets.hs, 3)



4. GAGE (Generally Applicable Gene-set Enrichment) analysis

# Get the results
keggres = gage(foldchanges, gsets=kegg.sets.hs, same.dir=T)
# T : UP, DOWN 각각에 특화된 ; F : UP, DOWN 모두 포함
str(keggres)
View(keggres)
# Look at both up (greater), down (less), and statatistics.
lapply(keggres, head)


5. 발현 변화 positive 5개, negative 5개 pathway

# Get the pathways
# 보고자 하는 발현 변화 (positive or negative 선택)
# positive
keggrespathways = rownames(lapply(keggres, head, 5)$greater)
# negative
keggrespathways = rownames(lapply(keggres, head, 5)$less)

# Get the IDs
keggresids = substr(keggrespathways, start=1, stop=8)
keggresids



6. 발현 변화 positive 5개, negative 5개 pathway

# Define plotting function
plot_pathway = function(pid) pathview(gene.data=foldchanges, pathway.id=pid, species="hsa")
# hsa03060 Protein export
plot_pathway("hsa03060")

#오른쪽 상단에 있는 range에서 볼 수 있듯이, 발현이 상대적으로 높을수록 red, 낮을수록 green 색을 보인다.

#PROTEIN EXPORT 패스웨이에 관여하는 유전자들이 구체적으로 어떤 위치에서 발현을 조절하는지 시각적으로 쉽게 확인 가능하다.

#Range와 Color는 모두 조절 가능하다.





7. 발현 변화 positive 5개의 pathway visualization

tmp = sapply(keggresids, plot_pathway)

#Expression 분석 결과는 해석하기 쉬우면서도 매우 어렵다....  

  A. 리소좀 Pathway의 발현이 전반적으로 증가했다 

  B. 전반적으로 발현이 증가했지만, 패스웨이 내 transport vesicle 기작들의 발현은 전반적으로 낮아졌다.

  C. 보통.. 발현 분석 결과 전체를 해석하기 보단, 본인이 연구하는 영역에 집중하여 합리적 근거로 해석한다.




pathview에서는 kegg pathway를 사용하므로

인간을 포함하여 mouse, yeast 등 여러 종을 기반으로 발현 분석해 볼 수 있겠다.





pathview (패스웨이 분석) End.

BioinformaticsAndMe





'R' 카테고리의 다른 글

while, for (R 반복문)  (0) 2019.09.16
R, as.Date (날짜 변환)  (0) 2019.06.03
R, 파일 입출력 (FILE I/O)  (0) 2018.09.11
R, T-test (R, T검정)  (0) 2018.08.29
R plot (그래픽스)  (0) 2018.08.27

R, 파일 입출력 (FILE I/O) Start.

BioinformaticsAndMe






R, FILE I/O


일반적으로 R programming의 작업 환경은 내문서에서 시작된다.


# 현재 디렉토리 위치를 반환하는 함수

getwd() 


> getwd()

[1] "C:/Users/home/Documents"



# 현재 디렉토리 위치를 바꾸는 함수

setwd() 


setwd("C:/Users/home/Desktop")
> getwd()
[1] "C:/Users/home/Desktop"



# 파일 읽기 함수

read.table()


>Input_data <- read.table("test.txt", header=TRUE, sep="\t", na.strings=c(".","NA"))


"test.txt" : 파일이름

header=TRUE : 헤더가 있는 경우 헤더를 사용하며, 만약 header 파라미터를 넣지 않으면 모두 데이터로 인식.

sep=" " : 구분자가 탭(\t)dm로 인식되는 경우.

na.strings=c(".", "nA") : 파일로부터 읽어온 값이 '.' 또는 'NA'인 경우 '결측치, Not Available (NA)'로 인식.

 



# 파일 쓰기 함수

write.table()


>write.table("result.txt", sep=",", quote=F, row.names=F)


sep=“,“ : 컬럼의 구분자를 쉽표(,)를 사용.

quote=F : 출력되는 값들의 Double Quotation(“”)를 제거하고 출력.

row.names=F : 데이터의 rowname 출력 X.







R, 파일 입출력 (FILE I/O) End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R, as.Date (날짜 변환)  (0) 2019.06.03
pathview (패스웨이 분석)  (2) 2019.05.22
R, T-test (R, T검정)  (0) 2018.08.29
R plot (그래픽스)  (0) 2018.08.27
R 회귀분석 (R regression test)  (0) 2018.08.19

R, T-test (R, T검정) Start.

BioinformaticsAndMe





1) one sample t-test

- 한 변수의 평균이 특정값과 같은지를 알아보기 위한 방법.


> bmi.ttest <- t.test(bmi, mu=30)

> bmi.ttest


        One Sample t-test


data:  bmi

t = 5.3291, df = 199, p-value = 2.661e-07

alternative hypothesis: true mean is not equal to 30

95 percent confidence interval:

 31.45521 33.16479

sample estimates:

mean of x 

    32.31 

--- P value가 0.05 이하이므로 귀무가설 기각 -> 평균이 30보다 크다는 대립가설채택


> names(bmi.ttest)

[1] "statistic"   "parameter"   "p.value"     "conf.int"    "estimate"    "null.value"  "alternative" "method"      "data.name"  

statistic: 검정통계랑

parameter: 파라미터

p.value: p값





2) two sample t-test

- 서로 독립적인 두 집단의 평균의 차이가 있는지를 확인.

- 집단 사이의 등분산 여부에 따라 분석방법이 달라지므로 등분산 검정 필요.


# 두 집단의 등분산 검정 / '~'는 type이라는 factor값에 의해 분류

> var.test(bmi ~ type) 

        F test to compare two variances


data:  bmi by type

F = 1.7595, num df = 131, denom df = 67, p-value = 0.01115

alternative hypothesis: true ratio of variances is not equal to 1

95 percent confidence interval:

 1.140466 2.637564

sample estimates:

ratio of variances 

           1.75945 

--- F 검정 결과 귀무가설을 기각하므로 등분산이 아님


> t.test(bmi ~ type) 


        Welch Two Sample t-test


data:  bmi by type

t = -4.512, df = 171.457, p-value = 1.188e-05

alternative hypothesis: true difference in means is not equal to 0

95 percent confidence interval:

 -5.224615 -2.044547

sample estimates:

 mean in group No mean in group Yes 

         31.07424          34.70882 

--- 당뇨의 유무에 따라 bmi의 차이가 있다고 결론





3) Paired t-test

- 쌍을 이룬 두 변수의 차이를 보는 검정.


예제데이터: anorexia

Treat: Factor of three levels: "Cont" (control), "CBT" (Cognitive Behavior treatment) and "FT" (family treatment).

Prewt: Weight of patient before study period, in lbs.

Postwt: Weight of patient after study period, in lbs.


# 서로 독립적인 두 집단의 평균을 비교 (평균이 같다/ 같지않다)

> attach(anorexia)

> FT <- subset(anorexia, Treat=='FT')

> head(FT)

   Treat Prewt Postwt

56    FT  83.8   95.2

57    FT  83.3   94.3

58    FT  86.0   91.5

59    FT  82.5   91.9

60    FT  86.7  100.3

61    FT  79.6   76.7


> shapiro.test(FT$Prewt - FT$Postwt)


        Shapiro-Wilk normality test


data:  FT$Prewt - FT$Postwt

W = 0.9536, p-value = 0.5156

--- 정규분포를 따른다


> t.test( FT$Prewt, FT$Postwt, paired=TRUE )

        Paired t-test

data:  FT$Prewt and FT$Postwt
t = -4.1849, df = 16, p-value = 0.0007003
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -10.94471  -3.58470
sample estimates:
mean of the differences 
              -7.264706 

--- P-value가 유의수준 0.05보다 작기 때문에, 가족치료를 실행하기 전, 후의 차이가 0이 아니라고 결론 내릴 수 있다.
-> 가족치료 효과가 있다고 판단 가능.







R, T-test (R, T검정) End.

BioinformaticsAndMe



'R' 카테고리의 다른 글

pathview (패스웨이 분석)  (2) 2019.05.22
R, 파일 입출력 (FILE I/O)  (0) 2018.09.11
R plot (그래픽스)  (0) 2018.08.27
R 회귀분석 (R regression test)  (0) 2018.08.19
R apply 함수  (0) 2018.08.15

R plot (그래픽스) Start.

BioinformaticsAndMe





plot( ) 함수 : x 와 y 의 2개 축을 기준으로 좌표를 찍어 그리는 함수



# R로 그림을 제작 시에는 고수준(high level)가 항상 먼저 호출되어야 한다.

# plot, boxplot 등의 고수준 함수를 먼저 그려야, 아래 points, lines 등의 저수준 함수를 덧그릴 수 있다.



# x , y축 값을 지정해서 출력하기

> x <- 1:3

> y <- 4:6

> plot(x, y)



# x , y 축 한계값(x축:1~5, y축:1~10) 조정하기

> x <- 1:3

> y <- 4:6

> plot(x, y, xlim=c(1,5), ylim=c(1,10))


#  x축과 y축 제목, 그래프제목 지정해서 출력

> x <- 1:3

> y <- 4:6

> plot(x, y, xlim=c(1,5), ylim=c(1,10), xlab="x축값", ylab="y축값", main="PLOT TEST")



# 여러 조건을 추가해서 그래프 만들기

> apple <- c(100,120,160,140,150)

> plot(apple, type="o", col="red", ylim=c(0,200), axes=FALSE, ann=FALSE)

> axis(1,at=1:5, lab=c("월","화","수","목","금"))

> axis(2,ylim=c(0,200))

> title(main="APPLE", col.main="red")

> title(xlab="요일", col.lab="black")

> title(ylab="가격", col.lab="blue")




# par(mfrow=c(#,#))

# 한 화면에 여러개의 그래프를 동시에 배치

# par (mfrow =c(행의 갯수, 열의 갯수)) 

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

> apple <- c(10,20,25,15,20)

> plot(apple, type=“p”)

> plot(apple, type=“o")

> plot(apple, type="l")




# 여러개의 그래프를 중첩으로 그리기 
# par(new=T) 를 그래프가 추가될 때마다 사용해야 함
> par(mfrow=c(1,1))
> y1 <- c(1,2,3,4,5)
> y2 <- c(2,3,4,5,6)
> y3 <- c(3,4,5,6,7)
> plot(y1, type="s", col="red", ylim=c(1,10))
# 중복허용
> par(new=T)
> plot(y2, type="o", col="green", ylim=c(1,10))
# 중복허용
> par(new=T)
> plot(y3, type="s", col="blue", ylim=c(1,10))



# lines( )함수를 사용하여 그래프를 중첩으로 그리기

y1 <- c(1,2,3,4,5)

y2 <- c(2,3,4,5,6)

y3 <- c(3,4,5,6,7)

plot(y1, type="s", col="red", ylim=c(1,10))

lines(y2, type="o", col="green", ylim=c(1,10))

lines(y3, type="s", col="blue", ylim=c(1,10))




# 범례 추가하기

# legend (x축위치, y축위치, 내용, cex=글자크기, col=색상, pch=크기, lty=선모양)

legend(4, 9, c("Y1","Y2","Y3"), cex=0.9, col=c("red", "green", "blue"), lty=1)

legend("topright", c("Y1","Y2","Y3"), cex=0.9, col=c("red", "green", "blue"), lty=1)








R plot (그래픽스) End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R, 파일 입출력 (FILE I/O)  (0) 2018.09.11
R, T-test (R, T검정)  (0) 2018.08.29
R 회귀분석 (R regression test)  (0) 2018.08.19
R apply 함수  (0) 2018.08.15
R 상관분석 (R correlation test)  (0) 2018.08.10

R 회귀분석 (R regression test) Start.

BioinformaticsAndMe




# R을 이용한 단순 선형 회귀분석(simple linear regression test)을 시작해보자.


(회귀분석에 대한 개념정리는 아래의 'Statistic' 카테고리에 있으니, 먼저 선행하고 오면 좋을 듯하다..!)

http://bioinformaticsandme.tistory.com/70?category=808983





# 선형회귀모델 (Linear regression model) 제작

> age=18:29

> age

 [1] 18 19 20 21 22 23 24 25 26 27 28 29

> height= 70:81

 [1] 70 71 72 73 74 75 76 77 78 79 80 81


# 나이에 따른 키를 plot() 함수를 이용하여, 나이에 따른 키의 scatterplot

> plot(x=age, y=height)


# 선형회귀모델의 최적선 구하기
# 좋은 선형회귀 모델이란것은 예측값과 실제 값의 차이를 뜻하는 잔차(Residual error)가 작은 모델
# R에서 회귀분석은 선형모형(linear model)을 쓴다.
# lm(종속변수(결과) ~ 독립변수(원인),데이터)
> res=lm(height~age)
> abline(res)

> res

Call:

lm(formula = height ~ age)


Coefficients:

(Intercept)          age  

     64.928        0.635  


#lm() 함수로 나온 결과는 다음과 같이 해석

intercept (y 절편) : 64.928

age (독립변수의 기울기): 0.635

키 = 0.635 * 나이 + 64.928 

height = 0.635*age + 64.928





# Galton 데이터를 예제로 회귀분석을 해보자.
> install.packages("UsingR")
> library(UsingR)
> data(galton) ; str(galton)

# galton 데이터는 928개의 부모의 키와 아이의 키에 대한 자료이다.
# 이 자료에 포함되어 있는 부모의 키는 아빠의 키와 1.08*엄마의 키의 평균이다.
# 이 자료들의 분포를 살펴보기 위해 화면을 둘로 나누고 히스토그램을 그려본다.

> par(mfrow=c(1,2))
> hist(galton$child, col="blue")
> hist(galton$parent, col="blue")
> par(mfrow=c(1,1))

# 부모의 키와 자녀의 키 사이의 수학적 관계를 나타내는 공식은 회귀분석을 통하여 구할 수 있다.

> out=lm(child~parent, data=galton)
> summary(out)

Call:
lm(formula = child ~ parent, data = galton)

Residuals:
    Min      1Q  Median      3Q     Max 
-7.8050 -1.3661  0.0487  1.6339  5.9264 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 23.94153    2.81088   8.517   <2e-16 ***
parent       0.64629    0.04114  15.711   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.239 on 926 degrees of freedom
Multiple R-squared:  0.2105, Adjusted R-squared:  0.2096 
F-statistic: 246.8 on 1 and 926 DF,  p-value: < 2.2e-16

결과의 마지막 세 줄을 살펴보자. Residual standard error(2.239인치) 라는 것은 이 모형을 사용하여, 부모키로부터 자녀키를 예측했을 때 평균 2.239인치의 오차가 생긴다는 뜻이다. Multiple R-squared가 0.210이라는 것은 이 모형은 자녀키 분산의 21.0%를 설명해준다는 뜻이다. 

# 결과를 보면 y절편(Intercept)이 23.94이고, parent의 기울기는 0.65인 것으로 나타난다.
# 즉 y=0.65x+23.94이다.
# 이를 그래프로 그려보면 다음과 같다.
> plot(child~parent,data=galton)
> abline(out,col="red")


# 위 그림을 ggplot2를 사용해 다시 그려보자.

> library(ggplot2)
> ggplot(data=galton, aes(x=parent,y=child)) +
geom_count() +
geom_smooth(method="lm")






R 회귀분석 (R regression test) End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R, T-test (R, T검정)  (0) 2018.08.29
R plot (그래픽스)  (0) 2018.08.27
R apply 함수  (0) 2018.08.15
R 상관분석 (R correlation test)  (0) 2018.08.10
막대그래프 (Barplot)  (0) 2018.08.06

+ Recent posts