R의 data.table로 데이터 조작하기
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 인수는 열 이름의 문자 벡터를 받습니다
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]
마찬가지로, 변수 목록(열 이름)을 사용하여 열을 선택할 수 있습니다
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
R의 data.table로 데이터 조작하기