使用 fread() 快速讀取資料

R 的 data.table 資料操作

Matt Dowle, Arun Srinivasan

Instructors, DataCamp

快到「飛」!

  • 快速、可平行的檔案讀取器
  • 參數 nThread 控制使用的執行緒數
R 的 data.table 資料操作

易用友善

  • 可匯入本機檔、網路檔與字串
  • 智慧預設值:colClassessepnrows 等等。
  • 注意:Date 與 Datetime 會先以字元欄讀入,可之後用優秀的 fasttimeanytime 套件轉換
R 的 data.table 資料操作

快速又友善的讀檔器

# 從 URL 讀檔
DT1<-fread("https://bit.ly/2RkBXhV")
DT1
a b
1 2
3 4
# 本機檔
DT2 <- fread("data.csv")
DT2
a b
1 2
3 4
# 字串
DT3 <- fread("a,b\n1,2\n3,4")
DT3
a b
1 2
3 4
# 無欄名的字串
DT4 <- fread("1,2\n3,4")
DT4
V1 V2
1  2
3  4
R 的 data.table 資料操作

nrows 與 skip 參數

# 只讀首行(標頭之後)
fread("a,b\n1,2\n3,4", nrows = 1)
a b
1 2
# 略過前兩行的中繼資料
str <- "# Metadata\nTimestamp: 2018-05-01 19:44:28 GMT\na,b\n1,2\n3,4"
fread(str, skip = 2)
a b
1 2
3 4
R 的 data.table 資料操作

更多 nrows 與 skip 用法

str <- "# Metadata\nTimestamp: 2018-05-01 19:44:28 GMT\na,b\n1,2\n3,4"
fread(str, skip = "a,b")
a b
1 2
3 4
fread(str, skip = "a,b", nrows = 1)
a b
1 2
R 的 data.table 資料操作

select 與 drop 參數

str <- "a,b,c\n1,2,x\n3,4,y"
fread(str, select = c("a", "c"))

# 同等於
fread(str, drop = "b")
a c
1 x
3 y
str <- "1,2,x\n3,4,y"
fread(str, select = c(1, 3))

# 同等於 
fread(str, drop = 2)
V1 V3
 1  x
 3  y
R 的 data.table 資料操作

一起來練習吧!

R 的 data.table 資料操作

Preparing Video For Download...