R apply 함수 Start.

BioinformaticsAndMe




# R apply() Function

- apply() : 데이터프레임 또는 매트릭스에 함수를 적용하여 행 또는 열 단위의 계산 수행.



apply( X, MARGIN, FUN)

- X : matrix

- MARGIN : 1(row) , 2(col)

- FUN : row/column 단위로 적용할 함수. 사용자가 만든 함수도 가능함.


EX1) apply(X, 1, sum)

EX2) apply(X, 2, sd)





# apply() 함수는 벡터, 행렬 등의 데이터 프레임에서 row/column 단위의 계산을 할 때 함수를 쉽게 적용할 수 있도록 도와준다.
# 실습데이터
> 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)


# weight, height만 추출
> patients.sub <- patients[ ,c("weight","height")]
> patients.sub
  weight height
1   65.4    170
2   55.0    155
3  380.0     NA
4   72.2    173
5   51.0    161
6     NA    166
 

# 각 환자(row)별로 몸무게와 키의 평균을 구한다
> apply(patients.sub, 1, mean)
[1] 117.7 105.0    NA 122.6 106.0    NA
 
# NA(결측치)는 빼고 계산한다
> apply(patients.sub, 1, mean, na.rm=TRUE)
[1] 117.7 105.0 380.0 122.6 106.0 166.0


# 각 특성(Column)별로 평균을 구한다

> apply(patients.sub, 2, mean, na.rm=TRUE)

weight height

124.72 165.00


# 각 셀에 2를 곱해준다

MulTwo <- function(x){ return(2*x) }

> apply(patients.sub, c(1,2), MulTwo)

     weight height

[1,]  130.8    340

[2,]  110.0    310

[3,]  760.0     NA

[4,]  144.4    346




#다양한 apply 함수군이 존재한다.

lapply: 결과를 리스트 형태로 반환

sapply: 벡터, 또는 행렬의 형태로 반환 (s: simplify)

tapply: 입력값을 index에 지정한 factor 값으로 분류(그룹화)하여 매개변수로 넘어온 function을 적용하는 함수다.



# lapply

> lapply( patients.sub, mean, na.rm = TRUE )
$weight
[1] 124.72
$height
[1] 165

# sapply
> sapply( patients.sub, mean, na.rm = TRUE )
weight height 
124.72 165.00 
 
# tapply
> patients$gender # categorical data
[1] M F M M F F
Levels: F M

> tapply(patients$weight, patients$gender, mean, na.rm=TRUE)
       F        M 
 53.0000 172.5333 




R apply 함수 End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R plot (그래픽스)  (0) 2018.08.27
R 회귀분석 (R regression test)  (0) 2018.08.19
R 상관분석 (R correlation test)  (0) 2018.08.10
막대그래프 (Barplot)  (0) 2018.08.06
R, 결측치 처리 (Missing value, NA)  (0) 2018.07.26

R 상관분석 (R correlation test) Start.

BioinformaticsAndMe




# R을 이용한 상관분석(correlation test)을 시작해보자.


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

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





# Pearson 상관분석은 변수들이 얼마나 직선적인 관계를 가지는지 분석하는 기법으로 상관계수를 이용하여 측정한다.

# 상관계수: Correlation coefficient


# 아이리스 예제데이터 불러오기

> attach(iris)


# cor() 함수 사용하여 상관계수 확인

> cor(Sepal.Length, Petal.Width)

[1] 0.8179411

# Pearson 상관계수: 0.8179


# cor.test() 함수로 Sepal.length와 Petal.Width간 상관계수 및 p-value, 신뢰구간을 구할 수 있다.

> cor.test(Sepal.Length, Petal.Width)


        Pearson's product-moment correlation


data:  Sepal.Length and Petal.Width

t = 17.2965, df = 148, p-value < 2.2e-16

alternative hypothesis: true correlation is not equal to 0

95 percent confidence interval:

 0.7568971 0.8648361

sample estimates:

      cor 

0.8179411 



# iris 데이터의 4가지 변수에 대해서 (Species를 제외한) 상관계수를 구해보자.

> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

#4x4 상관계수 행렬 ( 자기자신과의 상관계수는 항상 1이므로 대각선 element의 값은 모두 1.0000 )
> cor( iris[, 1:4] )
             Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length    1.0000000  -0.1175698    0.8717538   0.8179411
Sepal.Width    -0.1175698   1.0000000   -0.4284401  -0.3661259
Petal.Length    0.8717538  -0.4284401    1.0000000   0.9628654
Petal.Width     0.8179411  -0.3661259    0.9628654   1.000000
#시각화
pairs( iris[, 1:4] )







# 상관분석시, 결측치(Missing value)가 존재하는 경우 ##############
> iris.na.test <- iris[ ,1:4]
> iris.na.test[1, 1] <- NA
> iris.na.test[3, 2] <- NA
> iris.na.test[4, 3] <- NA
> head(iris.na.test)
  Sepal.Length Sepal.Width Petal.Length Petal.Width
1           NA         3.5          1.4         0.2
2          4.9         3.0          1.4         0.2
3          4.7          NA          1.3         0.2
4          4.6         3.1           NA         0.2
5          5.0         3.6          1.4         0.2
6          5.4         3.9          1.7         0.4

# cor() 함수의 결과는 모두 결측치를 반환한다. (NA가 연산에 포함되는 순간 그 결과값은 무조건 NA다.)
> cor( iris.na.test )
             Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length            1          NA           NA          NA
Sepal.Width            NA           1           NA          NA
Petal.Length           NA          NA            1          NA
Petal.Width            NA          NA           NA           1

# 결측치(NA)가 존재하는 데이터 row 벡터를 삭제하는 방법
> cor( iris.na.test, use="complete.obs")
             Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length    1.0000000  -0.1094799    0.8678973   0.8121441
Sepal.Width    -0.1094799   1.0000000   -0.4246671  -0.3610068
Petal.Length    0.8678973  -0.4246671    1.0000000   0.9615075
Petal.Width     0.8121441  -0.3610068    0.9615075   1.0000000
 

# 결측치(NA)가 존재하는 위치에서의 연산만 넘어가는 방법
> cor( iris.na.test, use="pairwise.complete.obs")

             Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length    1.0000000  -0.1097160    0.8696945   0.8169612
Sepal.Width    -0.1097160   1.0000000   -0.4299167  -0.3654865
Petal.Length    0.8696945  -0.4299167    1.0000000   0.9624433
Petal.Width     0.8169612  -0.3654865    0.9624433   1.0000000





R 상관분석 (R correlation test) End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R 회귀분석 (R regression test)  (0) 2018.08.19
R apply 함수  (0) 2018.08.15
막대그래프 (Barplot)  (0) 2018.08.06
R, 결측치 처리 (Missing value, NA)  (0) 2018.07.26
R, Command line interface Ⅱ  (0) 2018.07.20

막대그래프 (Barplot) Start.

BioinformaticsAndMe



barplot( ) 함수를 이용해 막대 그래프를 그려보자.

.


- 위 파라미터들은 barplot 에 사용되는 옵션이니 하나씩 테스트해보면 이해가 빠르겠다.





# 기본 bar 그래프

> x <- c(1,2,3,4,5)

> barplot(x)




# 그래프 가로로 출력 (horiz=T)

> x <- c(1,2,3,4,5)

> barplot(x, horiz=T)





# 그룹으로 묶어서 출력 (beside=T)
> x <- matrix(c(1,2,3,4),2,2)
> barplot(x, beside=T, names=1:2)





# 그룹으로 묶어서 가로로 출력(beside, horiz=T)

> x <- matrix(c(1,2,3,4),2,2)

> barplot(x, beside=T, horiz=T, names=1:2)

> barplot(x, horiz=T, names=1:2)





# 여러 가지 옵션을 추가하여 그래프 그리기

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

> barplot(apple, main= "Apple", xlab="요일", ylab="금액", names.arg=c("월","화","수","목","금"),  border="green", density=c(10,20,30,40,50))





# 여러 막대그래프를 그룹으로 묶어서 한꺼번에 출력

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

> peach <- c(180,200,210,190,170)

> berry <- c(110,150,160,90,120)

> fruits <- data.frame(APPLE=apple, PEACH=peach, BERRY=berry)

> fruits

  APPLE PEACH BERRY

1   100   180   110

2   120   200   150

3   140   210   160

4   130   190    90

5   150   170   120

> barplot(as.matrix(fruits), main="FRUITS", ylab="수량", beside=T, col=rainbow(5), ylim=c(0,400))

> legend("topright", c("월","화","수","목","금"), cex=0.8, fill=rainbow(5))




# 하나의 막대그래프에 여러가지 내용 출력하기

> barplot(t(fruits), main="FRUITS", ylab="판매량", ylim=c(0,900), col=rainbow(3), space=0.1, cex.axis=0.8, las=1, 

names.arg=c("월","화","수","목","금"), cex=0.8)

> legend(3.5, 900, names(fruits), cex=0.8, fill=rainbow(3))




# 조건을 주고 그래프 그리기

> peach <- c(180,200,210,190,170)

> colors <- c( )

> for( i in 1:length(peach)){

if (peach[i] >= 200) {colors <- c(colors, "red")}


else { colors <- c(colors, "blue")}


   }

> barplot(peach, main="PEACH", xlab="요일", ylab="수량", names.arg=c("월","화","수","목","금"), col=colors)






막대그래프 (Barplot) End.

BioinformaticsAndMe


'R' 카테고리의 다른 글

R apply 함수  (0) 2018.08.15
R 상관분석 (R correlation test)  (0) 2018.08.10
R, 결측치 처리 (Missing value, NA)  (0) 2018.07.26
R, Command line interface Ⅱ  (0) 2018.07.20
R, Command line interface Ⅰ  (0) 2018.07.16

R, 결측치 처리 (Missing value, NA) Start.

BioinformaticsAndMe



#R 작업시 발생하는 결측치 (missing value)를 다뤄보자.


-R 프로그래밍에서 결측지(missing value)는 NA (Not Available) 라는 문자로 처리해야 한다. NaN (Not a Number)는 분모를 0으로 나누는 것과 같이 계산이 불가능 할 경우 출력되는 문자다.

> y <- c(1,2,3, NA)

> y

[1]  1  2  3 NA


#is.na()는 벡터의 결측지가 존재할 경우 true

> is.na(y)

[1] FALSE FALSE FALSE  TRUE


> summary(y)

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
    1.0       1.5       2.0       2.0       2.5       3.0         1 

#NA는 missing value를 표현하는 논리형 자료이지만, "NA"는 문자열 그 자체이다.
> is.na( NA )
[1] TRUE
> is.na( "NA" )
[1] FALSE


#특정 값을 NA로 바꾸기 (-999 -> NA )

> ages <- c(48, 78, 56, 88, -999, 13, 26, -999)

> ages[ ages == -999] <- NA

> ages

[1] 48 78 56 88 NA 13 26 NA


#결측지(missing value)가 하나라도 포함된 데이터가 존재할 경우 연산의 결과 역시 NA가 된다. 따라서 함수 역시 아래와 같이 NA가 결과로 나온다.

> sum(ages)

[1] NA

> mean(ages)

[1] NA


#NA 데이터를 제외하고 연산하고 싶을 경우  na.rm = TRUE 매개변수를 넣어주면 된다.

> sum(ages, na.rm = TRUE)

[1] 309

> mean(ages, na.rm=TRUE)

[1] 51.5




#결측치 (missing value) 실습 예제


> 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)


> 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

> str(patients)
'data.frame':   6 obs. of  4 variables:
 $ weight  : num  65.4 55 380 72.2 51 NA
 $ height  : num  170 155 NA 173 161 166
 $ gender  : Factor w/ 2 levels "F","M": 2 1 2 2 1 1
 $ testDate: Factor w/ 5 levels "2013/09/01","2013/09/05",..: 1 1 2 3 4 5

#몸무게 측정을 거부한 환자 (6), 키 측정을 거부한 환자 (3)를 제외한 환자들 목록을 부르기
> na.omit(patients) # 해당 row 데이터를 삭제한 후 출력하는 방법
  weight height gender   testDate
1   65.4    170      M 2013/09/01
2   55.0    155      F 2013/09/01
4   72.2    173      M 2013/09/14
5   51.0    161      F 2013/10/11

# complete.cases(patients) # NA가 존재하는 경우 FALSE를 리턴

[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE


#patients[complete.cases(patients),] # complete.cases 함수 리턴값이 참인 경우를 출력하는 방법

  weight height gender   testDate

1   65.4    170      M 2013/09/01

2   55.0    155      F 2013/09/01

4   72.2    173      M 2013/09/14

5   51.0    161      F 2013/10/11


#patients 데이터에서 weight, height만 가져오기
> patients.sub <- patients[ ,c("weight","height")]
> patients.sub
  weight height
1   65.4    170
2   55.0    155
3  380.0     NA
4   72.2    173
5   51.0    161
6     NA    166

#patients.sub 데이터 연산하기
> apply(patients.sub, 2, mean) # patients.sub 데이터에 2: 열단위, mean 함수 적용
weight height 
    NA     NA 

#NA 데이터 삭제한 후 연산하기
> apply(patients.sub, 2, mean, na.rm=TRUE)
weight height 
124.72 165.00 




R, 결측치 처리 (Missing value, NA) End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R 상관분석 (R correlation test)  (0) 2018.08.10
막대그래프 (Barplot)  (0) 2018.08.06
R, Command line interface Ⅱ  (0) 2018.07.20
R, Command line interface Ⅰ  (0) 2018.07.16
R, RStudio 설치  (0) 2018.07.14

R, Command line interface  Start.

BioinformaticsAndMe



파트 1 에 이어서,

R 의 기본 명령어와 Component 를 다뤄보자.


8. 매트릭스에 row/column 추가하기

#Column 추가하기
> mat = matrix(1:20, ncol=4, nrow=5)
> cbind(mat, c(21:25) )
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25


#Row 추가하기

> mat = matrix(1:20, ncol=4, nrow=5)

> rbind(mat, c(26:29) )

     [,1] [,2] [,3] [,4]

[1,]    1    6   11   16

[2,]    2    7   12   17

[3,]    3    8   13   18

[4,]    4    9   14   19

[5,]    5   10   15   20

[6,]   26   27   28   29



9. 벡터에 이름 붙이기
> x <- c(1,2,3,4,5)
> names(x)
NULL
> names(x) <- c("A","B","C","D","E")
> x
A B C D E 
1 2 3 4 5 
> x['C']
> names(x)
[1] "A" "B" "C" "D" "E"


10. 매트릭스에 이름 붙이기
> CountTable <- matrix( c(189, 10845, 104, 10933) , nrow=2, byrow=TRUE )
> CountTable
     [,1]  [,2]
[1,]  189 10845
[2,]  104 10933
> rownames(CountTable) <- c("Placebo", "Aspirin")

> colnames(CountTable) <- c("No heart attack", "Heart attack")

> CountTable

        No heart attack Heart attack

Placebo           189        10845

Aspirin             104        10933

> CountTable["Placebo",]

No heart attack    Heart attack 

            189           10845 

> colnames(CountTable)

[1] "No heart attack" "Heart attack"



11. 범주형 변수 (factor)
#factor는 R에서 제공하는 categorical variable(범주형 변수)로, 여러개의 level로 구성된다. 혈액형이라는 범주형 변수가 존재할 때, A,B,AB,O 라는 level을 가지게 된다.
> BloodType <- c("A","B","AB","O","O","A","A","O","B","B")
> summary(BloodType)
   Length     Class      Mode 
       10 character character 
#위에서 정의한 BloodType이라는 vector를 factor로 형 변환.
> BloodType <- c("A","B","AB","O","O","A","A","O","B","B")
> BloodType <- factor(BloodType)
> BloodType
 [1] A  B  AB O  O  A  A  O  B  B 
Levels: A AB B O
#factor() 함수를 사용한 이후, BloodType은 A,AB,B,O라는 4가지 level을 가진 factor형 변수가 되고, 그것은 알파벳 순서로 정렬이 되어 categorical 하게 저장된다.
> summary(BloodType)
 A AB  B  O 
 3  1  3  3 

#성별 예시
> gender <- c(1,1,2,2,1,2,2,2,1,2)
> summary(gender)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    1.0     1.0     2.0     1.6     2.0     2.0 
> gender <- factor(gender)
> gender
 [1] 1 1 2 2 1 2 2 2 1 2
Levels: 1 2
> class(gender)
[1] "factor"
#1과 2의 level을 가지는 factor 형으로 변환된 것을 볼 수 있음. 하지만 1과 2가 무엇을 의미하는지 파악하기 불가능하기 때문에, 이름을 가지는 label을 구성해보자.
> gender <- c(1,1,2,2,1,2,2,2,1,2)
> gender <- factor(gender, levels=c(1,2), labels=c("male","female"))
> gender
 [1] male   male   female female male   female female female male   female
Levels: male female

 
12. 데이터 프레임 (data frame)
#벡터 데이터로 데이터프레임을 만드는 것은 data.frame()함수를 이용한다.
> head <- c("seoul", "tokyo", "paris")
> values <- 1:3
> sample <- data.frame(head, values)
#결과
   head     values
1 seoul             1
2 tokyo             2
3 paris             3 

#데이터프레임에 열 추가하기
> vec <- c(“100”, “80”, “30”) # 새로운 벡터데이터 생성하기
> sample$newcol <- vec #sample 데이터프레임에 벡터데이터(vec)추가

#데이터 열이름 바꾸기
방법1.
>names(sample)
# 결과
[1] "head" "values" 
방법2.
>names(sample)[names(sample) == "city"] <- c("C_NAME")
>names(sample) #열이름 출력
# 결과
[1] "C_NAME" "count" 
방법3.
>names(sample)[2] <- c("C_VLAUE")
>names(sample)#열이름 출력
# 결과
[1] "C_NAME" "C_VALUE"

#데이터 정렬
> data(mtcars)
> head(mtcars,10)
> order(mtcars$mpg)
> mtcars=mtcars[order(mtcars$mpg),]
> head(mtcars)


13. 데이터프레임 예제

#변속기가 자동(am == 0)이고 & 실린더가 4개, 6개 (cyl == c(4, 6)) 인 자동차들의 연비(mpg) 평균(mean())는?

> attach(mtcars)
# 변속기가 자동이고 & 실린더가 4개, 6개인 자동차의 연비, 실린더, 자동/수동 변수 선별
> mtcars_mart_0 <- mtcars[ which( am == 0 & cyl == c(4, 6)), c("mpg", "cyl", "am")]
> mtcars_mart_0
                mpg cyl am
Hornet 4 Drive 21.4   6  0
Valiant        18.1   6  0
Merc 230       22.8   4  0
Merc 280       19.2   6  0
Toyota Corona  21.5   4  0
> mean(mtcars_mart_0$mpg)
[1] 20.6
> detach(mtcars)



R, Command line interface  End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

막대그래프 (Barplot)  (0) 2018.08.06
R, 결측치 처리 (Missing value, NA)  (0) 2018.07.26
R, Command line interface Ⅰ  (0) 2018.07.16
R, RStudio 설치  (0) 2018.07.14
Permutation test (순열검정법)  (7) 2018.07.08

R, Command line interface Ⅰ Start.

BioinformaticsAndMe



R 의 기본 명령어와 Component 를 다뤄보자.


1. 변수 할당

-변수값 할당 연산자는 <-, <<-, = 를 사용한다.
-많은 소스에서 주요 연산자는 <- 를 사용한다. 
EX1) a <- 10
EX2) A <- 20

-알파벳, 숫자, _(언더바), .(마침표)로 구성된다.

- '-' (하이픈)은 사용불가.

-첫글자는 알파벳 또는 .(마침표)로만 시작해야 한다.

EX3) a-b <- 10
EX4) 1A <- 20


2. Data Type & Structure

R은 숫자형(numeric), 문자형(character), 논리형(logical) 그리고 복소수형(complex number) 총 4개의 저장 타입(storage mode)를 가지고 있으며 위의 type 하나 또는 그 이상의 조합으로 표현되는 벡터(vector), 행렬(matrix), 테이블(table), 데이터프레임(data frame), 리스트(list) 구조를 지닌다.
EX1) value <- 101 #numeric
EX2) string <- “bye” #character
EX3) logic <- 4 < 8 #logical
EX4) logic <- 4 != 8 #logical
EX5) mode(logic)


3. Basic operation
-벡터 값을 할당하기 위해서는 c() 라는 함수를 이용하여 할당할 수 있다.
-c : construct, combine, concatenate
EX1) x <- c(23, 34, 44)
EX2) x[1]

-숫자, 문자형이 혼재되어 있으면 문자형으로 강제 변환된다.
EX3) x <- c(1, 2, “R”)

-논리, 숫자형이 혼재되어 있으면 숫자형으로 강제 변환된다.
EX4) x <- c(1, 2, TRUE)


4. Element-wise
-R에서 벡터의 연산은 각 요소별로 pairwise하게 이뤄진다.
EX1) a <- c(1,2,3)
EX2) b <- c(4,5,6)
EX3) a*b
EX4) a <- c(1,2,3,4)
EX5) b <- c(4,5,6)
EX6) a*b


5. 벡터의 연산
> x <- 5;
> num <- c(100,500,1200)
> num/x
[1]  20 100 240

벡터변수 확인:
> num <- c(100,500,1200)
> num[1]
[1] 100
> num[2]
[1] 500
> num[3]
[1] 1200

Sequence의 선언:
> x=seq(from=0, to=2, by=0.5)
> y=seq(from=10, length=5)
> x
[1] 0.0 0.5 1.0 1.5 2.0
> y
[1] 10 11 12 13 14


6. 벡터의 조건문

EX1) x <- c(11, 12, 13, 14, 19, 20)

EX2) x > 15
EX3) x[x > 15]

-관계식에 맞는 index 추출
EX4) which( x > 15 )
EX5) which( x == 19 )


7.  행렬(Matrix) 다루기
-행렬의 선언
EX1) y <- matrix(1:20, nrow=5, ncol=4)
EX2) y <- matrix(1:20, nrow=5, ncol=4, byrow=TRUE)
-행렬 요소 추출
EX3) y[3, 2]
EX4) y[1, ]
EX5) y[ c(3,4), ]

-행렬 요소 치환
EX1) y[3, 2] <- 99
EX2) y[5, ] <- c(117, 118, 119, 120)
EX3) y[4, c(3,4)] <- c(115, 116)
-행렬의 연산
EX4) X <- matrix( 1:20, nrow=4)
EX5) sum(X)



R, Command line interface Ⅰ End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R, 결측치 처리 (Missing value, NA)  (0) 2018.07.26
R, Command line interface Ⅱ  (0) 2018.07.20
R, RStudio 설치  (0) 2018.07.14
Permutation test (순열검정법)  (7) 2018.07.08
Cogena-2 (CoExpression 분석)  (0) 2018.07.06

R, RStudio 설치 Start.

BioinformaticsAndMe



오픈소스 통계 프로그래밍 언어 R

R 통합개발 분석 환경 (IDE, Integrated Development Environment)인 RStudio 설치를 해보자.


1. R 설치

R은 Windows, MAC OS X, Linux 환경 모두에서 설치 가능하다. 여기서는 Window를 기준으로 설치를 진행한다.

R을 설치하려면 아래 보이는 공식사이트(https://www.r-project.org/)에서 R소프트웨어를 다운로드 한다. 
현재 최신버전은 3.5.1 (2018년07월02일) 이다.

아래의 download R을 클릭하면 R을 설치할 수 있는 Mirror 사이트로 연결된다. 





Mirror 사이트의 모습이다.
해당되는 국가 미러사이트에서 받는게 속도가 빠르다.




Window용을 클릭한 뒤 하위폴더에에서 install R for the first time을 선택하면 다운로드가 페이지가 뜬다.

여기서 Download R 3.5.1. for Windows를 클릭하면 다운로드 창이 보인다.

(나머지 과정은 생략하겠다.. 사진이 너무 많아..)


2. RStudio 설치

RStudio는 코드 직접실행, 구문강조, 괄호 자동입력지원, 명령어 완성, 다양한 단축키, 데이터 보기 및 가져오기, 그래픽 조작, 프로젝트 관리, 버전 관리 등의 다양한 기능을 제공한다. RStudio를 설치하기 위해서 RStudio 홈페이지로 이동한다. 

https://www.rstudio.com/


공식홈페이지에서 Download RStudio를 누르자.



클릭해서 들어가면 처음에 무슨 달러 써있고 이래서 놀랄 수 있는데, 가볍게 지나치고

스크롤을 내리면 아래 같은 화면이 나오고 해당 OS에 맞게 설치해주면 끝난다.


모든 설치가 끝나면 4개의 영역으로 구성된 RStudio를 볼 수 있겠다.

1. 소스 편집기 및 데이터view

2. R 콘솔

3. 작업환경과 히스토리

4. 파일, 플롯, 패키지, 도움말




R, RStudio 설치 End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R, Command line interface Ⅱ  (0) 2018.07.20
R, Command line interface Ⅰ  (0) 2018.07.16
Permutation test (순열검정법)  (7) 2018.07.08
Cogena-2 (CoExpression 분석)  (0) 2018.07.06
Cogena-1 (CoExpression 분석)  (0) 2018.07.05

Permutation test (순열검정법) Start.

BioinformaticsAndMe


Permutation test 는 t-test 등의 일반적인 통계 검정을 수행할 만큼 샘플의 수가 크지 않은 경우에 사용할 수 있는 검정 방법. 이 경우 주어진 샘플을 무작위로 추출하여 인공적으로 샘플 숫자를 늘림으로써 전체 모수를 통계 검정이 가능한 크기만큼 키운 다음, 원래 주어진 샘플의 통계 값(ex. 평균, 분산 등)이 전체 모수와 비교하여 얼마나 유의하게 차이 나는지를 검정하는 방법이다.



#‘저체중아의 산모’ vs ‘저체중아x의 산모’ 의 체중 차이를 Permutation test 해보자


1. birthwt 데이터 로딩
source("https://bioconductor.org/biocLite.R")
biocLite("MASS") #MASS package에 있는 birthwt 데이터셋을 사용하려함
library(MASS)
data(birthwt)
View(birthwt)


2. 정상군과 실험군 분류

normal = birthwt[birthwt[,"low"]==0, "lwt"]

normal

case = birthwt[birthwt[,"low"]==1, "lwt"]

case

t.test(normal, case)


3. 두 그룹의 산모 체중에 대한 t 검정 값

real_test = t.test(normal, case)$statistic 

real_test


4. 두 그룹간의 permutation test

permfunc.R

source("permfunc.R") #첨부파일 다운하여 실행

tperm = perm.test(normal, case, n.perm=1000) #1000번 Permutation을 통해 1000개의 t value 생성

hist(tperm)

abline(v=abs(real_test), lty=2, col=2) #실제 t value 가 분포의 극단치에서 보임 (우연이 아닐 것이라고 예상)

5. Empirical p value

pvalue = mean(abs(tperm) >= abs(real_test))  #위 그래프에서 Red 점선 오른쪽에 있는 개수들의 평균을 구함

pvalue

[1] 0.011

따라서, 계산된 Emprical p-value는 0.011로 '저체중아 출산과 산모의 체중은 관련성이 있다' 라고 결론 내릴 수 있다.


# 위 내용은 BITEC (Biomedical Informatics Training and Education Center) 교육내용을 참고하였다.


6. 실습 Example (위와 같은 맥락이지만, 연습삼아 해보셔도 좋을듯하다)

1) make up some ‘true’ data

carrier <- rep(c(0,1), c(100,200))

null.y <- rnorm(300)

alt.y <- rnorm(300, mean=carrier/2)

2) t-test

t.test(null.y~carrier, var.equal=TRUE)

t.test(alt.y~carrier, var.equal=TRUE)

3) permutation test

null.diff <- mean(null.y[carrier==1])-mean(null.y[carrier==0])
alt.diff <- mean(alt.y[carrier==1])-mean(alt.y[carrier==0])
one.test <- function(x,y) {
  xstar<-sample(x)
  mean(y[xstar==1])-mean(y[xstar==0])
}
many.truenull <- replicate(1000, one.test(carrier, null.y))
many.falsenull <- replicate(1000, one.test(carrier, alt.y))
4) 귀무가설 채택
hist(many.truenull)
abline(v=null.diff, lwd=2, col="purple")
mean(abs(many.truenull) > abs(null.diff))

5) 귀무가설 기각
hist(many.falsenull)
abline(v=alt.diff, lwd=2, col="purple")
mean(abs(many.falsenull) > abs(alt.diff))



마무리하며..

Permutation test 에 대한 간단한 R 예제를 살펴보았다.

통계검정 하려는 샘플 수가 적을 때 사용할 수 있는 기법이라는 점이 핵심으로 보인다.




Permutation test (순열검정법) End.

BioinformaticsAndMe

'R' 카테고리의 다른 글

R, Command line interface Ⅱ  (0) 2018.07.20
R, Command line interface Ⅰ  (0) 2018.07.16
R, RStudio 설치  (0) 2018.07.14
Cogena-2 (CoExpression 분석)  (0) 2018.07.06
Cogena-1 (CoExpression 분석)  (0) 2018.07.05

Cogena-2 (CoExpression 분석) Start.

BioinformaticsAndMe


Cogena-1 (CoExpression 분석) 에 이어지는 내용이다.


8. Drug enrichment analysis

Cogena 에서는 expression에 따른 클러스터에 관련된 Drug을 매칭해주는 작업을 말한다

# Drug data set

cmapDn100_cogena_result <- clEnrich_one(genecl_result, "pam", "10",

sampleLabel=sampleLabel, annofile=system.file("extdata", "CmapDn100.gmt.xz", package="cogena") )

summary(cmapDn100_cogena_result)


CmapDn100.gmt 을 보면 아래와 같은 테이블 형태이다


9. Drug repositioning

Drug repositioning : 임상에서 실패한 약물 or 시판되는 의약품을 재평가하여 새로운 약효를 찾는 방법

(Drug repositioning 은 깊게 들어가면 끝도 없으므로, 나중에 새로운 칼럼으로 다루겠다..)

heatmapPEI(cmapDn100_cogena_result, "pam", "10",  maintitle="Drug repositioning for Psoriasis")
# cluster 7 기준
heatmapCmap(cmapDn100_cogena_result, "pam", "10",  orderMethod = "7", maintitle="Drug repositioning for Psoriasis")

up expression 되어 있는 Cluster#7을 기준으로 'etoposide' 가 가장 Enrichment한 것이 보인다.

(에토포사이드 항암제로 쓰이는거 맞나?)


10. 클러스터 유전자 뽑기
# 4번 cluster 유전자
# Always make the number as character, please! (숫자에 quote 혹 double quote 해주란 얘기)
geneC <- geneInCluster(clen_res, "pam", "10", "4")
head(geneC)

11. 클러스터 expression matrix 뽑기
# Gene expression profiling with cluster information
# Always make the number as character, please!
gec <- geneExpInCluster(clen_res, "pam", "10")
gec$clusterGeneExp[1:3, 1:4]
gec$label[1:4]

12. Gene correlation 확인
# The gene correlation in a cluster
# Always make the number as character, please!
corInCluster(clen_res, "pam", "10", "10")

음 위에 그림은.. 파란색이 짙고 and 클수록 연결된 유전자 사이의 positive한 상관관계가 높다는 것을 의미한다.

반대로, 지금은 없지만, 빨간색이 짙고 and 클수록 해당 유전자 사이의 negative한 상관관계가 높다.

Correlation analysis에서 항상 명심해야하는 것은 상관관계가 높다고 절대 원인, 결과에 있는게 아니다..

예를 들어, FADS2 유전자 발현이 높은 것이 KRT79의 높은 발현의 원인이라 말할 수없다.

y=ax+b의 형태인 원인, 결과를 하고 싶다면, 회귀분석을 하자!



호호.. 끝났다. 사실 Cogena 툴은 상당히 돌리기 쉬운 축에 속하는 R package이다.
WGCNA 이란 비슷한 패키지도 있다는 것을 알아두자.
마지막으로, 발현 유전자 (DEG)를 분석하는 다양한 방법이 있다. 전체를 다 떄려 넣던지, Up|Down 따로 보던지, Cluster로 보던지...
정답은 없어 보인다. 생물학 연구에서 유전자 발현이란게 조직마다, 연구환경마다 너무나 다르기 때문에
여러 분석을 진행해보면서, 자신의 가설에 가장 적합한 방향으로 스터디를 진행하는 것이 좋을 듯 하다.



Cogena-2 (CoExpression 분석) End.

BioinformaticsAndMe



'R' 카테고리의 다른 글

R, Command line interface Ⅱ  (0) 2018.07.20
R, Command line interface Ⅰ  (0) 2018.07.16
R, RStudio 설치  (0) 2018.07.14
Permutation test (순열검정법)  (7) 2018.07.08
Cogena-1 (CoExpression 분석)  (0) 2018.07.05

Cogena-1 (CoExpression 분석) Start.

BioinformaticsAndMe



array 분석을 하다보면, 때로 수많은 DEG(Deferentially Expressed Gene) 형님들을 만나게 된다.

몇 천..?개는 다른 보정이 필요하겠고, 사실 몇 백개라도 골치 아프다.

아.. 수많은 DEG가지고 DAVID 돌려버리면 뭔가 두리뭉실한 기작만 나온다. GG



이럴때 나는

'Co-Expression 분석' 을 한다.


뭐 여러 정의가 있겠지만

간단히 말해서 유전자 발현(up, down) 양상이 비슷한 것 끼리 분석합시다.. 라고 나는 정의하겠다.

다시말해, 수많은 DEG들을 비슷한 발현양상을 갖는 그룹으로 클러스터링하여, 클러스터링된 DEG들의 기작을 살펴보는 것이다.

이것을 쉽게하기 위한 아래 R package를 추천한다.


'Cogena'

Co-expressed gene-set enrichment analysis 



논문에 나와있는 위 그림이 Cogena 를 단번에 설명해준다.

1. DEG 나옴.

2. 발현에따라 클러스터링 해줌 (클러스터링방법은많다).

3. 클러스터링 된 그룹에 무슨 Drug, Pathway가 Enrichment(빵빵)한지 분석을 해줌.




#############################################################################

BioinformaticsAndMe script

#############################################################################

1. cogena 패키지 설치

source("https://bioconductor.org/biocLite.R")

biocLite("cogena")

library(cogena)

# 예제(건선) 데이터 로딩

data(Psoriasis)

# 데이터 확인

ls()


2. Input data

# expression file

dim(DEexprs)

View(DEexprs)

# annotation file

sampleLabel

str(sampleLabel)

table(sampleLabel)


3. Pathway 데이터 로딩

# KEGG Pathway gene set

annoGMT <- "c2.cp.kegg.v5.0.symbols.gmt.xz“

# annotation 경로 지정

annofile <- system.file("extdata", annoGMT, package="cogena")

# GO 분석을 하고 싶다면,

# GO biological process gene set

# annoGMT <- "c5.bp.v5.0.symbols.gmt.xz"

아래표는 Cogena 가 가진 Annotation set이다. 잘 정리했군..


4. 파라미터 지정 (몇개 클러스터로 할건지, 무슨 clustering method를 쓸건지 등등)

# the number of clusters. It can be a vector.

# nClust <- 2:20

nClust <- 10

# Making factor "ct" , "Psoriasis"

sampleLabel <- factor(sampleLabel, levels=c("ct", "Psoriasis"))

# the clustering methods

# clMethods <- ("hierarchical","kmeans","diana","fanny","som","model",

# "sota","pam","clara","agnes") # All the methods can be used together.

clMethods <- c("hierarchical","pam")

# the distance metric

metric <- "correlation“

# the agglomeration method used for hierarchical clustering

method <- "complete"


5. Co-expression Analysis 시작

genecl_result <- coExp(DEexprs, nClust=nClust, clMethods=clMethods,

                       metric=metric, method=method)

summary(genecl_result)

# Enrichment (Pathway) analysis for the co-expressed genes

clen_res <- clEnrich(genecl_result, annofile=annofile, sampleLabel=sampleLabel)

summary(clen_res)


6. 클러스터링 결과 Heatmap 확인

# pam 클러스터링을 통해 10개의 클러스터 제작

# Always make the number as character, please!

# heatmap 그리기

heatmapCluster(clen_res, "pam", "10", maintitle="Psoriasis")



크... 일단 이쁘다.. 10개의 클러스티렁, up|down DEG, two샘플 그룹으로 heatmap이 만들어진다.

아! Pathway 봐야지!





7. 클러스터 Pathway 확인

# The enrichment score for 10 clusters, together with Down-regulated,Up-regulated and All DE genes.

heatmapPEI(clen_res, "pam", "10", maintitle="Pathway analysis for Psoriasis")

유전자 클러스터마다 어떤 pathway가 enrichment한지 보인다 (물론, 전체 only up, only down 도 볼 수있다).

옵션 조정해주면 특정 클러스터의 score 내림차순 기준으로 그림을 다시그려준다. 클러스터9 를 기준으로 다시그려보았다.




그림 왜이렇게 커...;;

Cogena-2 (CoExpression 분석) 에서 이어서 살펴보자.




Cogena-1 (CoExpression 분석) End.

BioinformaticsAndMe


'R' 카테고리의 다른 글

R, Command line interface Ⅱ  (0) 2018.07.20
R, Command line interface Ⅰ  (0) 2018.07.16
R, RStudio 설치  (0) 2018.07.14
Permutation test (순열검정법)  (7) 2018.07.08
Cogena-2 (CoExpression 분석)  (0) 2018.07.06

+ Recent posts