在r中创建一个基于其他列自动递增的列

时间:2014-12-18 05:26:45

标签: r

我的数据框包含customerID,产品和日期。我需要创建一个列,每当customerID或日期更改时生成一个事务ID。

我的数据框目前如下:

  1. 的CustomerID - 产品 - 日期
  2. 23 ------------- ABV ------- 14年12月12日
  3. 23个------------- GFS -------- 14年12月12日
  4. 18 ------------- GRA -------- 14年12月12日
  5. 52 ------------- WER -------- 14-12-14
  6. 23 ------------- QWE ------- 16-12-14
  7. 我需要使用r

    填充transactionID列
    1. 的CustomerID - 产品 - 日期---------- TRANSACTIONID
    2. 23 ------------- ABV ------- ---- 14年12月12日1
    3. 23个------------- GFS -------- 14年12月12日---- 1
    4. 18 ------------- GRA ------- ---- 14年12月12日2
    5. 52 ------------- WER ------- ---- 14-12-14 3
    6. 23 ------------- ------ QWE ---- 16-12-14 4
    7. 我在csv文件中有数据。我无法在Excel中创建此列,因为文件太大而且Excel无法打开整个文件。

      感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

假设列CustomerIDdate已订购,

indx <- as.character(interaction(df[c(1,3)]))
df$transactionID <- cumsum(c(TRUE,indx[-1]!=indx[-length(indx)]))
df$transactionID
#[1] 1 1 2 3 4

或者,如果列没有排序,例如,假设还有一行(6th row)与first row

重复
indx1 <- c(indx, indx[1])
as.numeric(factor(indx1, levels=unique(indx1)))
#[1] 1 1 2 3 4 1

或者

match(indx1, unique(indx1))
#[1] 1 1 2 3 4 1

数据

df <- structure(list(CustomerID = c(23L, 23L, 18L, 52L, 23L), Product =
c("abv", "gfs", "gra", "wer", "qwe"), date = c("12-12-14", "12-12-14", 
"12-12-14", "14-12-14", "16-12-14")), .Names = c("CustomerID", 
"Product", "date"), class = "data.frame", row.names = c(NA, -5L))

答案 1 :(得分:2)

根据您对我的评论的回复,您可能还会对来自&#34; data.table&#34;的.GRP感兴趣:

library(data.table)
## In case rows get out of order
DT <- as.data.table(df, keep.rownames = TRUE) 
DT[, transactionID := .GRP, by = list(CustomerID, date)][]
   rn CustomerID Product     date transactionID
1:  1         23     abv 12-12-14             1
2:  2         23     gfs 12-12-14             1
3:  3         18     gra 12-12-14             2
4:  4         52     wer 14-12-14             3
5:  5         23     qwe 16-12-14             4
相关问题