【问题标题】:data.table or dplyr - data manipulationdata.table 或 dplyr - 数据操作
【发布时间】:2014-02-20 10:04:50
【问题描述】:

我有以下数据

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

【问题讨论】:

  • 我正在寻找的输出是上面显示的日期和计数列。

标签: r data.table plyr data-manipulation dplyr


【解决方案1】:
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)]

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

【讨论】:

  • 太棒了!谢谢你。我更喜欢 data.table 选项。
  • 谢谢@Arun。我对数据表比较陌生。但我开始喜欢它了。 :)
  • 使用filtercol1 进行重复数据删除可能更有效(在dplyr 中),即df %.% arrange(Date) %.% filter(!duplicated(Col1)) %.% group_by(Date) %.% summarise(Count=length(Date)) %.% mutate(Count = cumsum(count))
  • 我支持@mnel - 如果你一直使用%.%,dplyr 代码看起来会好很多
  • @mnel 使用n() 代替length 可能也会更好。抄送@hadley
【解决方案2】:

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

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

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

您的数据必须先排序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多