การจัดการข้อมูลด้วย data.table ใน R
Matt Dowle, Arun Srinivasan
Instructors, DataCamp
อาร์กิวเมนต์ที่สอง j ใช้สำหรับ เลือก (และคำนวณ) คอลัมน์
# General form of data.table syntax
DT[i, j, by]
| | |
| | --> grouped by what?
| -----> what to do?
--------> on which rows?
อาร์กิวเมนต์ j รับ character vector ของชื่อคอลัมน์
ans <- batrips[, c("trip_id", "duration")]
head(ans, 2)
trip_id duration
139545 435
139546 432
batrips_df <- as.data.frame(batrips)
ans <- batrips_df[, "trip_id"]
head(ans, 2)
# The result is a vector, not a data.frame
139545, 139546
ans <- batrips[, "trip_id"]
# Still a data.table, not a vector
head(ans, 2)
trip_id
139545
139546
ใช้หมายเลขคอลัมน์แทนชื่อก็ได้เช่นกัน
ans <- batrips[, c(2, 4)]
head(ans, 2)
duration start_station
435 San Francisco City Hall
432 San Francisco City Hall
อย่างไรก็ตาม วิธีนี้ถือเป็น แนวปฏิบัติที่ไม่ดี
# If the order of columns changes, the result is wrong
batrips[, c(2, 4)]
# The result is always correct, no matter the order
batrips[, c("duration", "start_station")]
-c("col1", "col2", ...) ใช้ ยกเว้น คอลัมน์ที่ระบุ! แทน - ให้ผลเหมือนกัน# Select all cols *except* those shown below
ans <- batrips[, -c("start_date", "end_date", "end_station")]
head(ans, 1)
trip_id duration start_station start_terminal bike_id end_terminal
139545 435 San Francisco City Hall 58 65 473
subscription_type zip_code
Subscriber 94612
จำได้ไหมว่าในบทที่แล้ว คอลัมน์ถูกใช้เหมือนตัวแปรในอาร์กิวเมนต์ i?
# Recap the "i" argument
# All trips more than an hour
batrips[duration > 3600]
ในทำนองเดียวกัน สามารถใช้ list ของตัวแปร (ชื่อคอลัมน์) เพื่อเลือกคอลัมน์ได้
ans <- batrips[, list(trip_id, dur = duration)]
head(ans, 2)
trip_id dur
139545 435
139546 432
เมื่อเลือกคอลัมน์เดียว หากไม่ครอบตัวแปรด้วย list() จะได้ vector แทน
# Select a single column and return a data.table
ans <- batrips[, list(trip_id)]
head(ans ,2)
trip_id
139545
139546
# Select a single column and return a vector
ans <- batrips[, trip_id]
head(ans, 2)
139545 139546
.() คือชื่อย่อของ list() เพื่อความสะดวก
# .() is the same as list()
ans <- batrips[, .(trip_id, duration)]
head(ans, 2)
trip_id duration
139545 435
139546 432
การจัดการข้อมูลด้วย data.table ใน R