Loading data

Published by onesixx on

onesixx.com/fread

from Text

https://www.youtube.com/watch?v=aMYCFtoBrdA  by Gopal Malakar

fread

https://onesixx.com/fread/

dat파일 못읽음.
일반적인(각 행이 같은 열갯수를 가진 delimited files에 적용하고, 아닌면 read.table사용

txtString <- "
1 3 4 2 2 7
5 2 2 1 4 1
3 3 2 2 1 1
"
> fread(txtString)
   V1 V2 V3 V4 V5 V6
1:  1  3  4  2  2  7
2:  5  2  2  1  4  1
3:  3  3  2  2  1  1
> read.table(txtString)
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : cannot open file '
1 3 4 2 2 7
5 2 2 1 4 1
3 3 2 2 1 1
': No such file or directory

read.table() with textConnection()

read.table("A.txt", header=F, 
           sep = "|", fill=T, quote="", 
           stringsAsFactors=F)

read.table함수는 file을 소스로 읽어들이기 때문에, textConnection이라는 트릭이 필요하다.
없으면, Error in file(file, "rt") : cannot open the connection 이라는 에러발생

(따라서, Data를 저장된  txt파일로 만들어 사용할때도 있다.
Default로 구분자는 공백문자, 소수점으로 도트 문자 사용)

txtString <- "
Name physics math
Matthew 15 20
James 20 15
Messi NA 21
emily 44 100
Sixx 98 98
"
dd <- read.table(file=textConnection(txtString), 
                 header=T, sep=" ", stringsAsFactor=F) %>%data.table
closeAllConnections()

#---------------
dd %>% str
# Classes ‘data.table’ and 'data.frame': 5 obs. of  3 variables:
#  $ Name   : chr  "Matthew" "James" "Messi" "emily" ...
#  $ physics: int  15 20 NA 44 98
#  $ math   : int  20 15 21 100 98
#  - attr(*, ".internal.selfref")=
txtString <- "
1 3 4 2 2 7
5 2 2 1 4 1
3 3 2 2 1 1
"
con<- textConnection(txtString)
tt=read.table(con)
closeAllConnections()
#   V1 V2 V3 V4 V5 V6
# 1  1  3  4  2  2  7
# 2  5  2  2  1  4  1
# 3  3  3  2  2  1  1
https://onunicornsandgenes.blog/2014/03/06/using-r-common-errors-in-table-import/
DD <- read.table( "http://www-bcf.usc.edu/~gareth/ISL/Auto.csv",
                    header=T,
                    sep=",",
                    quote = "\\"", 
                    na.strings=c("NA", "-", "?"))

from Excel :: library(readxl)

https://cran.r-project.org/web/packages/readxl/index.html
http://blog.naver.com/hancury?Redirect=Log&logNo=220332744275

Hadley Wickham이 Rcpp로 개발한 readxl 패키지

read_excel(
  path,             # 엑셀파일의 경로
  sheet=1,          # String은 sheet명, integer는 sheet순(default 1)
  col_names=TRUE,   # 각 column의 이름 존재 유무 (X1,X2, ...Xn)
  col_types=NULL,   # "blank","numeric","date","text".
  na="",            # Missing value 처리 (default 빈칸)
  skip=0)           # skip할 행 

read_xlsx 또는 read_excel

library('readxl')
# 팩키지 제공 예제 Excel파일 
# /R/win-library/3.3/readxl/extdata/datasets.xlsx
src_file <- system.file("extdata/datasets.xlsx", package = "readxl") 

read_excel(src_file) %>% data.table()
read_excel(src_file, 2)          # 2번째 sheeet
read_excel(src_file, "mtcars")   # mtcars라는 이름의 sheet

excel_sheets

엑셀파일안에 모든 sheets를 보여준다.

sheets_names <- excel_sheets(src_file)
# Sheet명 "iris" "mtcars" "chickwts" "quakes"

# 활용예
excel_sheets(src_file) %>% map( read_excel, path=src_file)

from URL

Url에서 직접 로드

theUrl <- 'http://jaredlander.com/data/wifi.rdata'
con <- url(theUrl)
load(con)
close(con)

wifi %>% print() 

Url에서 다운받아서 로드

theUrl <- 'http://jaredlander.com/data/wifi.rdata'
# if (!file.exists("wifi.rdata") || now() > file.mtime("wifi.rdata") + weeks(4))
download.file(url=theUrl, destfile ="./data/wifi.rdata")
load("./data/wifi.rdata")
close("./data/wifi.rdata")

wifi %>% print() 

temp download.file unzip

url ="https://raw.githubusercontent.com/curiousily/TensorFlow-on-Android-for-Human-Activity-Recognition-with-LSTMs/master/data/WISDM_ar_v1.1_raw.txt"
download.file(url, destfile=file.path(DATA_PATH,"WISDM_ar_v1.1_raw.txt"))
# http://archive.ics.uci.edu/ml/datasets/Smartphone-Based+Recognition+of+Human+Activities+and+Postural+Transitions
URL="http://archive.ics.uci.edu/ml/machine-learning-databases/00341/HAPT%20Data%20Set.zip"
temp <- tempfile()
download.file(URL, temp)
unzip(temp, exdir=file.path(DATA_PATH,"HAPT"))
unlink(temp)

read.fwf()

fixed width file, 구분자가 아닌 고정된 폭 구조의 데이터

ff <- tempfile()

cat(file = ff, "123456", "987654", sep = "\
")
  read.fwf(ff, widths = c(1,2,3))    #> 1 23 456 \\ 9 87 654
  read.fwf(ff, widths = c(1,-2,3))   #> 1 456 \\ 9 654
unlink(ff)
#   V1 V2  V3
# 1  1 23 456
# 2  9 87 654
# 
#   V1  V2
# 1  1 456
# 2  9 654

cat(file = ff, "123", "987654", sep = "\
")
  read.fwf(ff, widths = c(1,0, 2,3))    #> 1 NA 23 NA \\ 9 NA 87 654
unlink(ff)
#   V1 V2 V3  V4
# 1  1 NA 23  NA
# 2  9 NA 87 654

cat(file = ff, "123456", "987654", sep = "\
")
  read.fwf(ff, widths = list(c(1,0, 2,3), c(2,2,2))) #> 1 NA 23 456 98 76 54
unlink(ff)
#   V1 V2 V3  V4 V5 V6 V7
# 1  1 NA 23 456 98 76 54

외부 CSV파일 한글깨짐 - mac

csv 데이터를 가져오는 방법은 fread와 read.csv(read.table) 정도가 있는데,
macbook을 사용하다보면 한글이 깨지는 경우가 많다. 이때 macos의 excel로 해당파일을 열어봐도 깨져있는경우는 os 자체가 제대로 지원하지 않는다고 볼수 있어, 원본 파일을 수정하는 방법밖에는 없다.
excel> DATA> from text (외부데이터가져오기)>
delimited 선택, file_origin:Korean(MacOS) > Comma> 완료.

https://onesixx.com/6-reading-data-into-r/

Categories: Reshaping

onesixx

Blog Owner