การอ่านไฟล์ขั้นสูง

การจัดการข้อมูลด้วย data.table ใน R

Matt Dowle, Arun Srinivasan

Instructors, DataCamp

การอ่านจำนวนเต็มขนาดใหญ่ด้วยประเภท integer64

  • โดยค่าเริ่มต้น R รองรับตัวเลขที่ไม่เกิน 2^31 - 1 = 2147483647
  • จำนวนเต็มขนาดใหญ่จะถูกอ่านเป็นประเภท integer64 ซึ่งมาจากแพ็กเกจ bit64 โดยอัตโนมัติ
ans <- fread("id,name\n1234567890123,Jane\n5284782381811,John\n")
ans
           id name
1234567890123 Jane
5284782381811 John
class(ans$id)
"integer64"
การจัดการข้อมูลด้วย data.table ใน R

การระบุประเภทคอลัมน์ด้วย colClasses

str <- "x1,x2,x3,x4,x5\n1,2,1.5,true,cc\n3,4,2.5,false,ff"

ans <- fread(str, colClasses = c(x5 = "factor")) str(ans)
Classes 'data.table' and 'data.frame':    2 obs. of  5 variables:
 $ x1: int  1 3
 $ x2: int  2 4
 $ x3: num  1.5 2.5
 $ x4: logi  TRUE FALSE
 $ x5: Factor w/ 2 levels "cc","ff": 1 2
การจัดการข้อมูลด้วย data.table ใน R

การระบุประเภทคอลัมน์ด้วย colClasses

ans <- fread(str, colClasses = c("integer", "integer", 
                                 "numeric", "logical", "factor"))
str(ans)
Classes 'data.table' and 'data.frame':    2 obs. of  5 variables:
 $ x1: int  1 3
 $ x2: int  2 4
 $ x3: num  1.5 2.5
 $ x4: logi  TRUE FALSE
 $ x5: Factor w/ 2 levels "cc","ff": 1 2
การจัดการข้อมูลด้วย data.table ใน R

การระบุประเภทคอลัมน์ด้วย colClasses

str <- "x1,x2,x3,x4,x5,x6\n1,2,1.5,2.5,aa,bb\n3,4,5.5,6.5,cc,dd"
ans <- fread(str, colClasses = list(numeric = 1:4, factor = c("x5", "x6")))
str(ans)
Classes 'data.table' and 'data.frame': 2 obs. of 6 variables:
 $ x1: num  1 3
 $ x2: num  2 4
 $ x3: num  1.5 5.5
 $ x4: num  2.5 6.5
 $ x5: Factor w/ 2 levels "aa","cc": 1 2
 $ x6: Factor w/ 2 levels "bb","dd": 1 2
การจัดการข้อมูลด้วย data.table ใน R

อาร์กิวเมนต์ fill

str <- "1,2\n3,4,a\n5,6\n7,8,b"
fread(str) 
V1 5 6
 7 8 b
Warning message:
In fread(str) :
  Detected 2 column names but the data has 3 columns (i.e. invalid file). 
  Added 1 extra default column name for the first column which is guessed to 
  be row names or an index. 
  Use setnames() afterwards if this guess is not correct, 
  or fix the file write command that created the file to create a valid file.
การจัดการข้อมูลด้วย data.table ใน R

อาร์กิวเมนต์ fill

fread(str, fill = TRUE)
V1 V2 V3
 1  2
 3  4  a
 5  6
 7  8  b
การจัดการข้อมูลด้วย data.table ใน R

อาร์กิวเมนต์ na.strings

ค่าที่หายไปมักถูกเข้ารหัสในรูปแบบ: "999" หรือ "##NA" หรือ "N/A"

str <- "x,y,z\n1,###,3\n2,4,###\n#N/A,7,9"
ans <- fread(str, na.strings = c("###", "#N/A"))
ans
x  y  z
1 NA  3
2  4 NA
NA 7  9
การจัดการข้อมูลด้วย data.table ใน R

มาฝึกกันเถอะ!

การจัดการข้อมูลด้วย data.table ใน R

Preparing Video For Download...