使用data.table基于条件创建二进制列

时间:2017-08-29 13:26:22

标签: r data.table

我有一个名为data的数据框。我正在尝试为每个CRD_NUMBIZ_DT创建一个0和1的新列。我将检查最大Jrny_Ind并将1分配给在该行中找到最大值的新列。

以下是要使用的数据:

  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分配新列。

2 个答案:

答案 0 :(得分:2)

这应该有重复。但就目前而言:

data[, last_trip := as.integer(Jrny_Ind == max(Jrny_Ind)), by = .(CRD_NUM, BIZ_DT)]

答案 1 :(得分:2)

使用 dplyr

library(dplyr)
dat %>% group_by(CRD_NUM, BIZ_DT) %>% 
        mutate(Last_Trip = as.integer(Jrny_Ind == max(Jrny_Ind)))

plyr

library(plyr)
ddply(dat,.(CRD_NUM, BIZ_DT),transform,Last_Trip =  as.numeric(Jrny_Ind == max(Jrny_Ind)))

<强> 输出:

dat
## # A tibble: 6 x 6
## # Groups:   CRD_NUM, BIZ_DT [3]
##    JRNY_ID_NUM      CRD_NUM    BIZ_DT Jrny_Ind last_trip Last_Trip
##          <dbl>        <dbl>    <fctr>    <int>     <int>     <int>
## 1 115485143065 1.000148e+15 03-Jan-17        1         0         0
## 2 115581455926 1.000148e+15 03-Jan-17        2         1         1
## 3 115542253339 1.000148e+15 04-Jan-17        1         0         0
## 4 115568253504 1.000148e+15 04-Jan-17        2         1         1
## 5 115579064996 1.000148e+15 05-Jan-17        1         0         0
## 6 115557373723 1.000148e+15 05-Jan-17        2         1         1