6

我有以下数据

Date           Col1       Col2
2014-01-01     123        12
2014-01-01     123        21
2014-01-01     124        32
2014-01-01     125        32
2014-01-02     123        34
2014-01-02     126        24
2014-01-02     127        23
2014-01-03     521        21
2014-01-03     123        13
2014-01-03     126        15

现在,我想计算Col1每个日期的唯一值(在前一个日期没有重复),并添加到前一个计数中。例如,

Date           Count
2014-01-01       3 i.e. 123,124,125
2014-01-02       5 (2 + above 3) i.e. 126, 127
2014-01-03       6 (1 + above 5) i.e. 521 only
4

2 回答 2

17
library(dplyr)
df %.% 
  arrange(Date) %.% 
  filter(!duplicated(Col1)) %.% 
  group_by(Date) %.% 
  summarise(Count=n()) %.% # n() <=> length(Date)
  mutate(Count = cumsum(Count))
# Source: local data frame [3 x 2]
# 
#         Date Count
# 1 2014-01-01     3
# 2 2014-01-02     5
# 3 2014-01-03     6

library(data.table)
dt <- data.table(df, key="Date")
dt <- unique(dt, by="Col1")
(dt <- dt[, list(Count=.N), by=Date][, Count:=cumsum(Count)])
#          Date Count
# 1: 2014-01-01     3
# 2: 2014-01-02     5
# 3: 2014-01-03     6

或者

dt <- data.table(df, key="Date")
dt <- unique(dt, by="Col1")
dt[, .N, by=Date][, Count:=cumsum(N)]

.NN为方便在这样的链式操作中自动命名(无点),因此如果需要,您可以在下一个操作中同时使用两者.N和一起使用。N

于 2014-01-28T21:43:35.227 回答
0

使用 ddply 和重复,你只需要做

df <- ddply(data, .(Date, Col1), nrow)
df2 <- ddply(df[!duplicated(df$Col1),], .(Date), nrow)
ddply(df2, .(Date, V1), nrow)

即,您首先计算所有夫妇的日期、Col1,然后删除重复的列。你终于数了数列。

您的数据必须先排序。

于 2014-01-28T21:38:56.897 回答