[Fast campus] Data Science with R 1기 - 이부일 강사님

공부하면서 배운 내용 복습 겸 정리하는 곳입니다.


Data Handling = Data Pre-processing


## 사용할 데이터 읽어오기

# 외부 데이터를 읽어오면 data.frame 형태로 저장된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
> student = readxl::read_excel(path = "fs/data/student.xlsx",
+                              sheet = "data",
+                              col_names = TRUE)
> student
# A tibble: 12 x 8
      id gender   age height weight  address
   <dbl>  <chr> <dbl>  <dbl>  <dbl>    <chr>
 1     1   남자    29    188     80   구파발
 2     2   남자    28    185     63     강동
 3     3   남자    25    172     63 압구정동
 4     4   여자    24    160     48     수원
 5     5   남자    26    180     80     용인
 6     6   남자    26    188     77     성수
 7     7   남자    59    170     63     수원
 8     8   여자    25    160     45     분당
 9     9   남자    27    178     78     강동
10    10   남자    31    181     95     의왕
11    11   여자    27    167     58     길동
12    12   남자    40    175     70     부산
# ... with 2 more variables: major <chr>,
#   company <chr>
cs


1. 데이터 전체보기

  (1) View(데이터) 

View(student)

# 별도의 팝업 창으로 데이터를 볼 수 있음

  

  (2) 데이터 : 콘솔(Console)에 출력

student



2. 데이터 구조(Structure) 보기

  (1) str(데이터)

str(student)

1
2
3
4
5
6
7
8
9
10
> str(student)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':    12 obs. of  8 variables:
 $ id     : num  1 2 3 4 5 6 7 8 9 10 ...
 $ gender : chr  "남자" "남자" "남자" "여자" ...
 $ age    : num  29 28 25 24 26 26 59 25 27 31 ...
 $ height : num  188 185 172 160 180 188 170 160 178 181 ...
 $ weight : num  80 63 63 48 80 77 63 45 78 95 ...
 $ address: chr  "구파발" "강동" "압구정동" "수원" ...
 $ major  : chr  "경영정보학" "산업경영학" "경영학" "수학" ...
 $ company: chr  "NC소프트" "구글" "아마존" "SK" ...
cs

# student의 id만 보고 싶다면 => str(student$id)



3. 데이터의 일부 보기

  (1) head(데이터) 

# 상위 6개의 데이터를 보여줌

1
2
3
4
5
6
7
8
9
10
11
12
> head(student)
# A tibble: 6 x 8
     id gender   age height weight  address
  <dbl>  <chr> <dbl>  <dbl>  <dbl>    <chr>
1     1   남자    29    188     80   구파발
2     2   남자    28    185     63     강동
3     3   남자    25    172     63 압구정동
4     4   여자    24    160     48     수원
5     5   남자    26    180     80     용인
6     6   남자    26    188     77     성수
# ... with 2 more variables: major <chr>,
#   company <chr>
cs

# head(student, n = 3)

# 출력 데이터 개수 지정 가능

  

  (2) tail(데이터)

# 하위 6개의 데이터를 보여줌

# head와 동일한 출력 형태

# tail(student)

# tail(student, n = 3)



4. 데이터 프레임의 속성

  (1) 행의 개수 : nrow(데이터)

1
2
> nrow(student)
[112
cs


  (2) 열의 개수 => 변수의 개수 : ncol(데이터)

1
2
> ncol(student)
[18
cs


  (3) 행의 이름 : rownames(데이터)

# 결과는 character

1
2
3
> rownames(student)
 [1"1"  "2"  "3"  "4"  "5"  "6"  "7"  "8" 
 [9"9"  "10" "11" "12"
cs

  

  (4) 열의 이름 => 변수의 이름 : colnames(데이터)

# 결과는 character

1
2
3
> colnames(student)
[1"id"      "gender"  "age"     "height" 
[5"weight"  "address" "major"   "company"
cs


  (5) 차원(dimension) : 행, 렬 : dim(데이터)

1
2
3
4
5
6
7
8
> dim(student)
[112  8
 
> dim(student)[1
[112
 
> dim(student)[2
[18
cs


  (6) 차원의 이름 : 행의 이름, 열의 이름 : dimnames(데이터)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
> dimnames(student)
[[1]]
 [1"1"  "2"  "3"  "4"  "5"  "6"  "7"  "8" 
 [9"9"  "10" "11" "12"
 
[[2]]
[1"id"      "gender"  "age"     "height" 
[5"weight"  "address" "major"   "company"
 
> dimnames(student)[1#리스트
[[1]]
 [1"1"  "2"  "3"  "4"  "5"  "6"  "7"  "8" 
 [9"9"  "10" "11" "12"
 
> dimnames(student)[[1]] #벡터
 [1"1"  "2"  "3"  "4"  "5"  "6"  "7"  "8" 
 [9"9"  "10" "11" "12"
 
> dimnames(student)[[1]][3#벡터(dimnames(student)[[1]]) 의 3번 째 값
[1"3"
cs


5. 데이터(data.frame)의 슬라이싱

  # 데이터[행index, 열index] => data.frame은 행,열의 2차원 구조

  # Vectorization 이 적용됨, for문 없이 연산이 끝까지 수행


  (1) 열(column) 

# 데이터[ , index]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> student[ , 2]
# A tibble: 12 x 1
   gender
    <chr>
 1   남자
 2   남자
 3   남자
 4   여자
 5   남자
 6   남자
 7   남자
 8   여자
 9   남자
10   남자
11   여자
12   남자
cs


문제. 짝수번째 열 가져오기

1
2
3
student[ , seq(from = 2,
               to   = ncol(student),
               by   = 2)] 
cs

# vector 에서는 length

# data.frame 에서는 nrow, ncol


문제. weight, height의 데이터를 가져오기

1
student[ , c("weight""height")
cs

# index가 character 이므로 c( )를 사용


# 변수명에 특정한 패턴이 있는 것을 추출

# grep("패턴", 문자열)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 변수명 중에서 'e'라는 글자를 포함하고 있는 변수명의 위치
grep("e"
     colnames(student))
 
# 'e'라는 글자를 포함하고 있는 변수명
grep("e"
     colnames(student), 
     value=TRUE
 
# 'e'라는 글자를 포함하고 있는 데이터를 추출
student[ , grep("e"
                colnames(student), 
                value=TRUE)]
 
# 'a'라는 글자로 시작하는 데이터를 추출 => ^a
student[ , grep("^a"
                colnames(student), 
                value=TRUE)]
 
# 't'라는 글자로 끝나는 데이터를 추출 => t$
student[ , grep("t$"
                colnames(student), 
                value=TRUE)]
 
# 't'라는 글자로 끝나거나, 'a'라는 글자로 시작하는 데이터를 추출
student[ , grep("t$|^a"
                colnames(student), 
                value=TRUE)]
cs

# 정규표현식을 익히자

# https://wikidocs.net/1669 

# http://www.nextree.co.kr/p4327/


  (2) 행(row)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 성별이 여자인 데이터만 가져오기
student.female = student[student$gender == "여자"]
 
# 거주지가 수원이 아닌 사람들의 데이터
student[student$address != "수원"]
 
# 몸무게가 50 이하인 사람들의 데이터
student[student$weight <= 50]
 
# 나이가 30대 이상이고, 키는 175 이상인 사람
student[(student$age >= 30& (student$height >= 175), ]
 
# 나이가 30대 이상이거나 키는 175 이상인 사람
student[(student$age >= 30| (student$height >= 175), ]
cs


  (3) 행, 열

1
2
3
4
# 키가 170cm 이상이고, 몸무게가 60kg 이상인 사람들 중에서 
# 변수명에 'e'라는 글자가 들어가는 데이터
student[(student$height >= 170& (student$weight >= 60), 
        grep("e", colnames(student))]
cs








[Fast campus] Data Science with R 1기 - 이부일 강사님

공부하면서 배운 내용 복습 겸 정리하는 곳입니다.


IV. 배열(Array)
  # 다차원
  # vector, 행렬의 확장
  # 벡터의 특징( Recycling Rule, Vectorization ) 그대로 적용됨
  # array(vector, dim=)
1
2
> array(1:10, dim=10)
 [1]  1  2  3  4  5  6  7  8  9 10
cs
  # dim에 1개의 숫자
  # 1차원 형태를 지닌 벡터의 결과

1
2
3
4
5
> array(1:10, dim=3:4)
     [,1[,2[,3[,4]
[1,]    1    4    7   10
[2,]    2    5    8    1
[3,]    3    6    9    2
cs
  # dim에 3,4 => 2개의 숫자
  # 2차원 형태를 지닌 행렬의 결과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
> array(1:10, dim=c(3,4,2))
, , 1
 
     [,1[,2[,3[,4]
[1,]    1    4    7   10
[2,]    2    5    8    1
[3,]    3    6    9    2
 
, , 2
 
     [,1[,2[,3[,4]
[1,]    3    6    9    2
[2,]    4    7   10    3
[3,]    5    8    1    4
cs
  # dim에 숫자 3,4,2 => 3개의 숫자
  # 3행 4열 2높이 => 3차원


V. 데이터 프레임(Data.Frame)
  # 행, 열로 구성. 2차원
  # 여러 개의 데이터 유형을 가질 수 있음 
  # 단, 하나의 열은 하나의 데이터 유형만 가짐 
  # data.frame(벡터1, 벡터2, 행렬, ...)
1
2
3
4
5
6
7
8
9
10
11
> id = 1:5
> gender = c("m""m""m""f""m")
> address = c("구파발""강동""압구정""수원""용인")
> survey = data.frame(id, gender, address)
> survey
  id gender address
1  1      m  구파발
2  2      m    강동
3  3      m  압구정
4  4      f    수원
5  5      m    용인
cs


VI. 리스트(List)
  # 분석한 결과를 저장할 때에 많이 사용하는 형태
  # 가장 유연한 데이터 형태
  # 리스트의 원소로 vector, factor, matrix, array, data.frame, list를 가질 수 있다.
  # list(vector, factor, matrix, array, data.frame, list, ...)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
> v1 = 1:10
> v2 = 1:3
> v3 = c("ch""nu""lo")
> v4 = c(TRUEFALSE)
> m1 = cbind(v1, v2)
> result = list(v1, v2, v3, v4, m1, survey)
> result
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10
 
[[2]]
[11 2 3
 
[[3]]
[1"ch" "nu" "lo"
 
[[4]]
[1]  TRUE FALSE
 
[[5]]
      v1 v2
 [1,]  1  1
 [2,]  2  2
 [3,]  3  3
 [4,]  4  1
 [5,]  5  2
 [6,]  6  3
 [7,]  7  1
 [8,]  8  2
 [9,]  9  3
[10,] 10  1
 
[[6]]
  id gender address
1  1      m  구파발
2  2      m    강동
3  3      m  압구정
4  4      f    수원
5  5      m    용인
 
cs

  리스트의 슬라이싱
  # 리스트의 슬라이싱은 [ ] , [[ ]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
> a1 = result[1]
> a2 = result[[1]]
> a1
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10
 
> a2
 [1]  1  2  3  4  5  6  7  8  9 10
 
> b1 = result[4]
> b2 = result[[4]]
> b1
[[1]]
[1]  TRUE FALSE
 
> b2
[1]  TRUE FALSE
cs

  # 대괄호 1개 사용 : 결과는 list

  # 대괄호 2개 사용 : numeric, character, logical, list로 나타남.

 


+ Recent posts