7/24 (화) 42차시

matrix(행렬)

-벡터처럼 한 가지 유형의 스칼라 값만 저장
-matrix 함수를 이용해 행렬을 생성한다
-행과 열을 지정

x<-c(1:9); x
## [1] 1 2 3 4 5 6 7 8 9
x<-matrix(c(1:9),nrow=3); x #nrow=행의 갯수
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
x<-matrix(c(1:9), ncol=3); x    #ncol=열의 갯수
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
x<-matrix(c(1:9), nrow=3, ncol=3); x    #3X3행렬
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
x<-matrix(c(1:9), ncol=1); x
##       [,1]
##  [1,]    1
##  [2,]    2
##  [3,]    3
##  [4,]    4
##  [5,]    5
##  [6,]    6
##  [7,]    7
##  [8,]    8
##  [9,]    9
nrow(x); ncol(x); dim(x) #행, 열의 수
## [1] 9
## [1] 1
## [1] 9 1
x<-matrix(c(1:9), nrow=3, byrow=TRUE); x    #행부터 값을 채운다
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
## [3,]    7    8    9
x<-matrix(c(1,2,3,4), nrow=2, byrow=TRUE,
      dimnames=list(c("row1","row2"),c("col1","col2"))); x #dimnames :행과 열에 이름 부여
##      col1 col2
## row1    1    2
## row2    3    4
x<-matrix((1:9), ncol=3)
dimnames(x)<-list(c('a1','a2','a3'),c('c1','c2','c3')); x
##    c1 c2 c3
## a1  1  4  7
## a2  2  5  8
## a3  3  6  9
rownames(x)<-c('r1','r2','r3'); x   #행의 이름 수정
##    c1 c2 c3
## r1  1  4  7
## r2  2  5  8
## r3  3  6  9
colnames(x)<-c('b1','b2','b3'); x   #열의 이름 수정
##    b1 b2 b3
## r1  1  4  7
## r2  2  5  8
## r3  3  6  9

개별적인 값들을 모아 행렬 만들기

cells<-c(1:9)
rname<-c('r1','r2','r3')
cname<-c('c1','c2','c3')

x<-matrix(cells, nrow=3, byrow=TRUE, dimnames=list(rname, cname)); x
##    c1 c2 c3
## r1  1  2  3
## r2  4  5  6
## r3  7  8  9
class(x)    #자료의 형태
## [1] "matrix"
mode(x) #자료값의 타입
## [1] "numeric"

행렬 내에서 특정 자료 출력 :행렬 이름[행 인덱스, 열 인덱스]

x[1,1]; x[2,1]; x[3,2]; x[1, ]; x[ ,2]
## [1] 1
## [1] 4
## [1] 8
## c1 c2 c3 
##  1  2  3
## r1 r2 r3 
##  2  5  8
x[1,-2]; x[1,2:3]; x[c(1,3),c(1,2)]
## c1 c3 
##  1  3
## c2 c3 
##  2  3
##    c1 c2
## r1  1  2
## r3  7  8
x['r1',]; x[ ,'c2']
## c1 c2 c3 
##  1  2  3
## r1 r2 r3 
##  2  5  8

행렬의 연산

x<-matrix(c(1:4), ncol=2)
x+10; x-10; 10-x; x*10; x/10; x+x
##      [,1] [,2]
## [1,]   11   13
## [2,]   12   14
##      [,1] [,2]
## [1,]   -9   -7
## [2,]   -8   -6
##      [,1] [,2]
## [1,]    9    7
## [2,]    8    6
##      [,1] [,2]
## [1,]   10   30
## [2,]   20   40
##      [,1] [,2]
## [1,]  0.1  0.3
## [2,]  0.2  0.4
##      [,1] [,2]
## [1,]    2    6
## [2,]    4    8
x-x; x/x; x*x #행렬값의 제곱꼴 출력
##      [,1] [,2]
## [1,]    0    0
## [2,]    0    0
##      [,1] [,2]
## [1,]    1    1
## [2,]    1    1
##      [,1] [,2]
## [1,]    1    9
## [2,]    4   16
x%*%x #제대로 계산된 행렬의 곱
##      [,1] [,2]
## [1,]    7   15
## [2,]   10   22
t(x)    #전치행렬 :행과 열의 위치 변경
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4
solve(x)    #역행렬
##      [,1] [,2]
## [1,]   -2  1.5
## [2,]    1 -0.5
x%*%solve(x)    #단위행렬
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1
x<-matrix(c(1:6), ncol=3); x
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
dim(x); x
## [1] 2 3
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
dim(x)<-c(3,2); x   #dim으로 행과 열의 수를 변경
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6
x<-matrix(c(1:9), nrow=3)
y<-matrix(c(1:9), nrow=3)
x; y
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
cbind(x, y) #열을 기준으로 합침
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    4    7    1    4    7
## [2,]    2    5    8    2    5    8
## [3,]    3    6    9    3    6    9
rbind(x, y) #행을 기준으로 합침
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
## [4,]    1    4    7
## [5,]    2    5    8
## [6,]    3    6    9

array(배열)

-같은 데이터 타입을 갖는 3차원 배열구조
-matrix는 2차원 행렬, array는 3차원 행렬
-array 함수를 이용해 배열 생성

x<-array(c(1:6), dim=c(2,3)); x
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
x<-array(c(1:24), dim=c(2,3,4)); x
## , , 1
## 
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
## 
## , , 2
## 
##      [,1] [,2] [,3]
## [1,]    7    9   11
## [2,]    8   10   12
## 
## , , 3
## 
##      [,1] [,2] [,3]
## [1,]   13   15   17
## [2,]   14   16   18
## 
## , , 4
## 
##      [,1] [,2] [,3]
## [1,]   19   21   23
## [2,]   20   22   24
x[1,1,]; x[1,,]; x[,,4]
## [1]  1  7 13 19
##      [,1] [,2] [,3] [,4]
## [1,]    1    7   13   19
## [2,]    3    9   15   21
## [3,]    5   11   17   23
##      [,1] [,2] [,3]
## [1,]   19   21   23
## [2,]   20   22   24
dimnames(x)<-list(c('r1','r2'),c('c1','c2','c3')); x
## , , 1
## 
##    c1 c2 c3
## r1  1  3  5
## r2  2  4  6
## 
## , , 2
## 
##    c1 c2 c3
## r1  7  9 11
## r2  8 10 12
## 
## , , 3
## 
##    c1 c2 c3
## r1 13 15 17
## r2 14 16 18
## 
## , , 4
## 
##    c1 c2 c3
## r1 19 21 23
## r2 20 22 24
rownames(x); colnames(x)
## [1] "r1" "r2"
## [1] "c1" "c2" "c3"
class(x); mode(x); str(x); is.matrix(x); is.array(x)
## [1] "array"
## [1] "numeric"
##  int [1:2, 1:3, 1:4] 1 2 3 4 5 6 7 8 9 10 ...
##  - attr(*, "dimnames")=List of 3
##   ..$ : chr [1:2] "r1" "r2"
##   ..$ : chr [1:3] "c1" "c2" "c3"
##   ..$ : NULL
## [1] FALSE
## [1] TRUE

factor(팩터)

-범주형 :데이터를 미리 정해진 유형으로 분류
-level :A,B,C,D,E / 좋음,보통,나쁨
-종류 :순서형(ordinal), 명목형(nominal)
-순서형(ordinal) :데이터 간 순서를 둘 수 있는 경우(A,B,C,D,E..)
-명목형(nominal) :데이터 간 크기 비교가 불가능한 경우(남,여)
-factor는 분류작업에 용이하지 연산작업에는 적합하지 않다.

x<-factor('좋음', c('좋음','보통','나쁨')); x   #c()로 레벨 지정. factor는 레벨에 있는 값을 써줘야한다
## [1] 좋음
## Levels: 좋음 보통 나쁨
str(x); class(x) ;mode(x)
##  Factor w/ 3 levels "좋음","보통",..: 1
## [1] "factor"
## [1] "numeric"
y<-factor('좋음', c('좋음','보통','나쁨'), ordered=TRUE); y #ordered=레벨의 크기 지정
## [1] 좋음
## Levels: 좋음 < 보통 < 나쁨
str(y); class(y); mode(y); nlevels(y)   #레벨의 갯수
##  Ord.factor w/ 3 levels "좋음"<"보통"<..: 1
## [1] "ordered" "factor"
## [1] "numeric"
## [1] 3
levels(y)                #레벨의 목록
## [1] "좋음" "보통" "나쁨"
levels(y)[1]; levels(y)[2]; levels(y)[3]    #레벨 각 위치에 해당되는 값
## [1] "좋음"
## [1] "보통"
## [1] "나쁨"
levels(y)<-c('good','normal','bad'); y
## [1] good
## Levels: good < normal < bad
is.factor(y); is.factor(x)
## [1] TRUE
## [1] TRUE
is.ordered(y)   #is.ordered( )=순서형인지 확인
## [1] TRUE
is.ordered(x)
## [1] FALSE
gender<-factor(c('male','male','female'),c('male','female')); gender
## [1] male   male   female
## Levels: male female
x<-ordered(c('a','b'), c('a','b','c')); x; is.ordered(x)
## [1] a b
## Levels: a < b < c
## [1] TRUE
x<-factor(c('large','medium','small','small','large','medium'), levels=c('small','medium','large')); x
## [1] large  medium small  small  large  medium
## Levels: small medium large
x<-append(x,'tiny',after=6); x  #레벨값 작성은 문자형으로 했으나 내부적으로 숫자로 받아들임
## [1] "3"    "2"    "1"    "1"    "3"    "2"    "tiny"
x<-as.vector(x); x      #팩터형이 되며 숫자가 된 레벨값들을 문자형으로 형 변환
## [1] "3"    "2"    "1"    "1"    "3"    "2"    "tiny"
x<-as.factor(x); x      #위에서 문자형으로 바꾸었던 값들을 팩터형으로 형 변환
## [1] 3    2    1    1    3    2    tiny
## Levels: 1 2 3 tiny

data frame(데이터 프레임)

-각기 다른 데이터 타입을 갖는 컬럼으로 이루어진 2차원 테이블 구조
(DB의 TABLE과 유사)
-data.frame( ) 함수를 이용해 각 컬럼, 행을 구성한다.

df<-data.frame(x=c(1,2,3,4,5), y=c(6,7,8,9,10)); df
##   x  y
## 1 1  6
## 2 2  7
## 3 3  8
## 4 4  9
## 5 5 10
mode(df); class(df); str(df); df$x; df$y
## [1] "list"
## [1] "data.frame"
## 'data.frame':    5 obs. of  2 variables:
##  $ x: num  1 2 3 4 5
##  $ y: num  6 7 8 9 10
## [1] 1 2 3 4 5
## [1]  6  7  8  9 10
df<-data.frame(name=c('scott', 'harden', 'curry'),sql=c(90,80,70),
        plsql=c(70,80,90)); df
##     name sql plsql
## 1  scott  90    70
## 2 harden  80    80
## 3  curry  70    90
str(df) #데이터 프레임에서 문자형 변수를 입력하면 팩터형이 된다.
## 'data.frame':    3 obs. of  3 variables:
##  $ name : Factor w/ 3 levels "curry","harden",..: 3 2 1
##  $ sql  : num  90 80 70
##  $ plsql: num  70 80 90
df<-data.frame(name=c('scott', 'harden', 'curry'),sql=c(90,80,70),
        plsql=c(70,80,90),stringsAsFactors=FALSE); df
##     name sql plsql
## 1  scott  90    70
## 2 harden  80    80
## 3  curry  70    90
str(df) #stringsAsFactors=FALSE :데이터 프레임에 있는 문자형 변수의 팩터형 전환을 막는다
## 'data.frame':    3 obs. of  3 variables:
##  $ name : chr  "scott" "harden" "curry"
##  $ sql  : num  90 80 70
##  $ plsql: num  70 80 90

값을 수정하는 방법

df[1,1]<-'james'; df
##     name sql plsql
## 1  james  90    70
## 2 harden  80    80
## 3  curry  70    90

특정 컬럼을 확인

df$sql; df$plsql
## [1] 90 80 70
## [1] 70 80 90

특정 값을 확인

df[1,1]; df[1,2:3]; df[,2]; df[-1,-2]; df[c(1,3),2]
## [1] "james"
##   sql plsql
## 1  90    70
## [1] 90 80 70
##     name plsql
## 2 harden    80
## 3  curry    90
## [1] 90 70
df[,c('sql', 'plsql')]; df[,'sql', drop=FALSE]  #drop=FALSE :원래의 모양대로 출력
##   sql plsql
## 1  90    70
## 2  80    80
## 3  70    90
##   sql
## 1  90
## 2  80
## 3  70
df$sql[1]; df$sql[2]
## [1] 90
## [1] 80

특정 컬럼을 추가

df$r<-c(80,70,60); df
##     name sql plsql  r
## 1  james  90    70 80
## 2 harden  80    80 70
## 3  curry  70    90 60

특정 컬럼을 삭제

df$r<-NULL; df
##     name sql plsql
## 1  james  90    70
## 2 harden  80    80
## 3  curry  70    90
x<-data.frame(1:3); x
##   X1.3
## 1    1
## 2    2
## 3    3
colnames(x)<-c('val'); rownames(x)<-c('a','b','c'); x
##   val
## a   1
## b   2
## c   3
colnames(x); names(x)
## [1] "val"
## [1] "val"
names(x)<-c('col'); names(x)
## [1] "col"
d<-data.frame(a=1:3, b=4:6, c=7:9); d
##   a b c
## 1 1 4 7
## 2 2 5 8
## 3 3 6 9
names(d)%in%c('b','c')
## [1] FALSE  TRUE  TRUE
d[,names(d)%in%c('b','c')]  #특정컬럼 추출
##   b c
## 1 4 7
## 2 5 8
## 3 6 9
d[,!names(d)%in%c('b','c')] #조건에 해당하지 않는 경우의 컬럼 추출
## [1] 1 2 3
d[,-c(2, 3)]
## [1] 1 2 3
d[4,]<-c(7,7,7); d  #행 추가
##   a b c
## 1 1 4 7
## 2 2 5 8
## 3 3 6 9
## 4 7 7 7
d<-d[-4,]; d        #행 삭제
##   a b c
## 1 1 4 7
## 2 2 5 8
## 3 3 6 9
x<-data.frame(x=1:50); x;
##     x
## 1   1
## 2   2
## 3   3
## 4   4
## 5   5
## 6   6
## 7   7
## 8   8
## 9   9
## 10 10
## 11 11
## 12 12
## 13 13
## 14 14
## 15 15
## 16 16
## 17 17
## 18 18
## 19 19
## 20 20
## 21 21
## 22 22
## 23 23
## 24 24
## 25 25
## 26 26
## 27 27
## 28 28
## 29 29
## 30 30
## 31 31
## 32 32
## 33 33
## 34 34
## 35 35
## 36 36
## 37 37
## 38 38
## 39 39
## 40 40
## 41 41
## 42 42
## 43 43
## 44 44
## 45 45
## 46 46
## 47 47
## 48 48
## 49 49
## 50 50
head(x) #앞부분의 데이터
##   x
## 1 1
## 2 2
## 3 3
## 4 4
## 5 5
## 6 6
tail(x) #뒷부분의 데이터
##     x
## 45 45
## 46 46
## 47 47
## 48 48
## 49 49
## 50 50
tail(x, n=10); head(x, n=10)
##     x
## 41 41
## 42 42
## 43 43
## 44 44
## 45 45
## 46 46
## 47 47
## 48 48
## 49 49
## 50 50
##     x
## 1   1
## 2   2
## 3   3
## 4   4
## 5   5
## 6   6
## 7   7
## 8   8
## 9   9
## 10 10
#특정 행을 제한한다고 할 때 d[,-c('b','a')]로 작성하면 에러 발생.
#d[,-c(2,3)] 혹은 d[,!names(d)%in%c('b','c')], d[,names(d)%in%c('b','c')] 으로 제한, 추출한다.