1
我有一個數據幀,名爲data
。我正在嘗試爲每個CRD_NUM
和BIZ_DT
創建一個0和1的新列。我將檢查最大值Jrny_Ind
並將1指定給在該行中找到最大值的新列。使用data.table基於條件創建二進制列
這裏的數據一起工作:
structure(list(JRNY_ID_NUM = c(115485143065, 115581455926, 115542253339,
115568253504, 115579064996, 115557373723), CRD_NUM = c(1000148004095169,
1000148004095169, 1000148004095169, 1000148004095169, 1000148004095169,
1000148004095169), BIZ_DT = structure(c(3L, 3L, 4L, 4L, 5L, 5L
), .Label = c("01-Jan-17", "02-Jan-17", "03-Jan-17", "04-Jan-17",
"05-Jan-17", "06-Jan-17", "07-Jan-17", "08-Jan-17", "09-Jan-17",
"10-Jan-17", "11-Jan-17", "12-Jan-17", "13-Jan-17", "14-Jan-17",
"15-Jan-17", "16-Jan-17", "17-Jan-17", "18-Jan-17", "19-Jan-17",
"20-Jan-17", "21-Jan-17", "22-Jan-17", "23-Jan-17", "24-Jan-17",
"25-Jan-17", "26-Jan-17", "27-Jan-17", "28-Jan-17", "29-Jan-17",
"30-Jan-17", "31-Jan-17"), class = "factor"), Jrny_Ind = c(1L,
2L, 1L, 2L, 1L, 2L)), .Names = c("JRNY_ID_NUM", "CRD_NUM", "BIZ_DT",
"Jrny_Ind"), class = c("data.table", "data.frame"), row.names = c(NA,
-6L), .internal.selfref = <pointer: 0x0000000002640788>)
所需的輸出:
JRNY_ID_NUM CRD_NUM BIZ_DT Jrny_Ind Last_Trip
1: 115485143065 1000148004095169 03-Jan-17 1 0
2: 115581455926 1000148004095169 03-Jan-17 2 1
3: 115542253339 1000148004095169 04-Jan-17 1 0
4: 115568253504 1000148004095169 04-Jan-17 2 1
5: 115579064996 1000148004095169 05-Jan-17 1 0
6: 115557373723 1000148004095169 05-Jan-17 2 1
我試圖讓每張卡的 「最大行數」 和日期如下圖所示:
data[, .SD[which.max(Jrny_Ind)], by = c("CRD_NUM","BIZ_DT")]
不確定如何使用data.table
分配新列。
'數據[,last_trip:= +(Jrny_Ind == MAX(Jrny_Ind)),由=(CRD_NUM,BIZ_DT)。]'(或'as.integer'代替' +') – Jaap
'library(dplyr); %>%group_by(CRD_NUM,BIZ_DT)%> mutate(Last_Trip = as.integer(Jrny_Ind == max(Jrny_Ind)))'% – Masoud