R/R기초

R02_CSV, 엑셀파일에서 데이터 프레임 만들기

Codezoy 2019. 9. 27. 09:00

Goals
  • 데이터 프레임 생성, 헤더가 없는 csv 파일에서 데이터프레임 생성, Separation : 콤마( , ) 대신 콜론 ( : ) 사용, MS Excel 읽어서 데이터프레임 생성( readxl )

Notes

# 현재 작업 디렉토리(폴더) 확인
>> getwd ( )

# 현재 작업 디렉토리 변경
>> setwd ('c:/dev/lab-r')

#  ./data/csv_exam.csv  파일을 읽어서 데이터 프레임 생성 : read.csv('데이터 디렉토리')
   exam_csv = read.csv('data/csv_exam.csv')

  # 데이터 프레임의 내용을 확인
> exam_csv
   id class math english science
1   1     1   50      98      50
2   2     1   60      97      60
3   3     1   45      86      78

  # 수학 점수들의 합계
> sum(exam_csv$math)
[1] 1149

# 각 학생들의 수학 영어 과학 점수 합계
> total = exam_csv$math+exam_csv$english+exam_csv$science


#  헤더가 없는 csv 파일에서 데이터프레임 생성
<원본>
<수정>

> exam_csv2=read.csv("data/exam_nohead.csv")
Error in make.names(col.names, unique = TRUE) :
  invalid multibyte string 1

> exam_csv2 <- read.csv('data/exam_nohead.csv', header=FALSE)
> exam_csv2
        V1 V2 V3 V4 V5
1  癤<bf>1  1 50 98 50                                인코딩이 깨져서 한문이 나옴
2        2  1 60 97 60
3        3  1 45 86 78
4        4  1 30 98 58

> exam_csv2 <- read.csv('data/exam_nohead.csv', header=FALSE,
                                             fileEncoding = 'UTF-8-BOM')
> exam_csv2
   V1 V2 V3 V4 V5                                       # 문제 해결, 대문자로 적어야 함.
1   1  1 50 98 50
2   2  1 60 97 60
3   3  1 45 86 78
4   4  1 30 98 58


>> 콤마( , ) 대신 콜론 ( : ) 사용
>> csv 파일 수정
>> sep의 기본값 : 쉼표 ' ,  '


> exam_csv3 = read.csv("data/csv_exam2.csv",
                        header= TRUE,
                       sep = ':',
                       fileEncoding = 'UTF-8-BOM')
> exam_csv3
  id class math english science
1  1     1   50      98      50


<MS Excel file (xls, xlsx)을 읽어서 데이터 프레임을 생성>
# readxl 패키지를 설치
# install.packages("readxl")
# Tools -> install packages -> readxl 입력

# Excel을 직접 읽기 위한 패키지 사용
readxl:::read_excel('data/excel_exam.xlsx')

# 매번 readxl:: 입력하기 싫을 때 : 설치한 패키지를 검색경로에 추가한 후 사용 -> library 함수 사용
> library(readxl)

# 패키지가 검색 경로에 추가됐는지 확인 
> search ( ) 

# 실행
> library('readxl')
> exam_xlsx = read_excel('data/excel_exam.xlsx')
> exam_xlsx
# A tibble: 20 x 5
      id class  math english science
   <dbl> <dbl> <dbl>   <dbl>   <dbl>
1     1     1    50      98      50
2     2     1    60      97      60
3     3     1    45      86      78
4     4     1    30      98      58

#수학 점수 출력
> exam_xlsx$math
[1] 50 60 45 30 25 50 80 90 20 50 65 45 46 48 75 58 65 80 89 78

# 엑셀 파일에서 첫 번째 행이 컬럼(변수) 이름이 아닌 경우
> exam_xlsx_nohead = read_excel('data/exam_nohead.csv')
Error: Can't establish that the input is either xls or xlsx.

> exam_xlsx_nohead = read_excel('data/excel_exam_novar.xlsx',
                                col_names = FALSE)             # TRUE = T, FALSE = F
New names:
* `` -> ...1
* `` -> ...2
* `` -> ...3
* `` -> ...4
* `` -> ...5

> exam_xlsx_nohead
# A tibble: 8 x 5
   ...1  ...2  ...3  ...4  ...5
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     1    50    98    50
2     2     1    60    97    60
3     3     2    25    80    65

# 컬럼 이름을 직접 만들어 줄 수 있다
> exam_xlsx_nohead = read_excel('data/excel_exam_novar.xlsx',
                                 col_names = c('id','cl','m','e','s'))
> exam_xlsx_nohead
# A tibble: 8 x 5
     id    cl     m     e     s
  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     1    50    98    50
2     2     1    60    97    60
3     3     2    25    80    65


# 엑셀 파일에서 특정 sheet에 있는 데이터를 읽는 경우
> exam_xlsx_sheet = read_excel('data/excel_exam_sheet.xlsx',
                                sheet = 3)
> exam_xlsx_sheet
# A tibble: 8 x 5
     id class  math english science
  <dbl> <dbl> <dbl>   <dbl>   <dbl>
1     1     1    50      98      50
2     2     1    60      97      60
3     3     2    25      80      65



# 데이터 프레임을 CSV 파일로 저장하기
> write.csv(exam_xlsx)
"","id","class","math","english","science"
"1",1,1,50,98,50
"2",2,1,60,97,60
"3",3,1,45,86,78
"4",4,1,30,98,58