การแปลง data.tables

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

Scott Ritchie

Postdoctoral Researcher in Systems Genomics

การ cast data.table แบบ long

sales_wide <- dcast(sales_long, quarter ~ year, value.var = "amount")

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

ฟังก์ชัน dcast()

รูปแบบทั่วไปของ dcast():

dcast(DT, ids ~ group, value.var = "values")
      |   |     |                   |
      |   |     |                    --> column to split
      |   |      ----------------------> group labels to split by
      |    ----------------------------> rows to keep behind as identifiers
       --------------------------------> data.table to reshape            
การ Join ข้อมูลด้วย data.table ใน R

ฟังก์ชัน dcast()

sales_wide <- dcast(sales_long, quarter ~ year, value.var = "amount")

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

การแยกคอลัมน์ค่าหลายคอลัมน์

dcast(profit_long, quarter ~ year, value.var = c("revenue", "profit"))

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

Row identifier หลายคอลัมน์

เก็บหลายคอลัมน์เป็น row identifier:

dcast(sales_long, quarter + season ~ year, value.var = "amount")

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

การตัดคอลัมน์ออก

ผลลัพธ์จะมีเฉพาะคอลัมน์ที่ระบุใน formula หรือ value.var เท่านั้น:

sales_wide <- dcast(sales_long, quarter ~ year, value.var = "amount")

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

การจัดกลุ่มหลายระดับ

แยกตามคอลัมน์กลุ่มหลายคอลัมน์:

dcast(sales_long, quarter ~ department + year, value.var = "amount")

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

การแปลงเป็น matrix

sales_wide <- dcast(sales_long, season ~ year, value.var = "amount")
sales_wide
   season    2015    2016
1: Autumn 3420000 3670000
2: Spring 2950000 3000300
3: Summer 2980700 3120200
4: Winter 3200100 3350000
การ Join ข้อมูลด้วย data.table ใน R

การแปลงเป็น matrix

as.matrix() สามารถกำหนดคอลัมน์ที่ต้องการใช้เป็น rownames ของ matrix ได้:

mat <- as.matrix(sales_wide, rownames = "season")
mat
       2015    2016        
Autumn 3420000 3670000
Spring 2950000 3000300
Summer 2980700 3120200
Winter 3200100 3350000
การ Join ข้อมูลด้วย data.table ใน R

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

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

Preparing Video For Download...