[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기 - 이부일 강사님

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


외부 데이터 : txt, csv, excel(xls, xlsx) 


1. 텍스트 데이터 : txt

  (1) 구분자(Separator) : 공백 하나(blank, white space)

1
2
3
데이터명 = read.table(file  = "파일위치/파일명.txt",
                     header = TRUE,
                     sep    = " "
cs


  (2) 구분자(Separator) : comma(,)

1
2
3
데이터명 = read.table(file   = "파일위치/파일명.txt",
                     header = TRUE,
                     sep    = ","
cs


  (3) 구분자(Separator) : 탭(tab)

1
2
3
데이터명 = read.table(file   = "파일위치/파일명.txt",
                     header = TRUE,
                     sep    = "\t"
cs



2. CSV(Comma Separated Value)

# 엑셀의 특수한 형태

1
2
3
데이터명 = read.table(file   = "파일위치/파일명.txt",
                     header = TRUE,
                     sep    = "\t"
cs


3. 엑셀 : xls, xlsx

# R의 기본 기능에서는 못 읽어 옴

# 추가 기능(패키지(Package))을 설치 - install.packages("패키지명")

# 패키지 로딩하기, 구동하기 - library(패키지명)

1
2
3
4
5
6
> install.packages("readxl")
package ‘readxl’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:\Users\JungChul\AppData\Local\Temp\RtmpG8Gy4u\downloaded_packages
> library(readxl)
cs

  # 패키지 설치 명령어 후 successfully 메시지가 나오면 설치 완료

  # 패키지는 항상 코드 가장 위( 다른 pc에서 실행 할 수도 있으니 install.packages명령어도 같이 적어두기 )

  # 패키지 내 함수를 사용할 때는 '패키지명::함수' 형태로 사용하자

1
2
3
데이터명 = readxl::read_excel(path="파일위치/파일명.xlsx",
                             sheet=index or "시트명",
                             col_names=TRUE)
cs


+ Recent posts