【问题标题】:Running stats in R [duplicate]在 R 中运行统计数据 [重复]
【发布时间】:2014-03-01 06:14:56
【问题描述】:

以下是我拥有的示例数据框。

    Year - Revenue
    2001  1.23
    2002 23.4
    2003 12.4
    2004 18.0
    ...

我正在计算运行统计数据 - 例如同比增长。这将是收入 [2002] - 收入 [2001]。

我可以使用 for 循环来做到这一点。但是 plyr 中是否有基本功能或任何东西可以更优雅地完成此任务?

【问题讨论】:

  • ?diff

标签: r dplyr plyr


【解决方案1】:

正如建议的那样,diff 会满足您的需求。如果您的数据集很大或有组,您可以尝试 dplyr。

require(dplyr)

dat <- read.table(header = TRUE, text = "Year Revenue
2001  1.23
2002 23.4
2003 12.4
2004 18.0")

mutate(dat, yoy = Revenue - lag(Revenue))

  Year Revenue    yoy
1 2001    1.23     NA
2 2002   23.40  22.17
3 2003   12.40 -11.00
4 2004   18.00   5.60

编辑:回复 Eddi 的评论。数据的复制方式似乎也存在一些差异。请参阅下面 dplyr 的changes 的输出。

> dplyr_dat <- mutate(dat, yoy = Revenue - lag(Revenue))
> dplyr::changes(dat, dplyr_dat)
Changed variables:
          old new        
yoy           0x10d951400

Changed attributes:
          old         new        
names     0x10c3161b8 0x10deeb128
class     0x101ca6568 0x103668108
row.names 0x10c233f88 0x100c98a68
> diff_dat <- within(dat, yoy <- c(NA, diff(Revenue)))
> dplyr::changes(dat, diff_dat)
Changed variables:
          old         new        
Year      0x10c316180 0x11086b9f0
Revenue   0x1036b2120 0x1070c0f28
yoy                   0x110118a40

Changed attributes:
          old         new        
names     0x10c3161b8 0x10c310ff8
class     0x101ca6568 0x10f4ce7a8
row.names 0x10c1d6a38 0x10f7dca78

【讨论】:

  • mutate 在大型数据集上的执行速度会比diff 快吗?仅供参考@user3273226,diff 方法可能如下所示:within(dat, yoy &lt;- c(NA, diff(Revenue)))
  • @jbaums - diffmutate 的微基准测试表明,对于 400K 长度的向量,时间改进为 30ms 与 15ms,对于 2M 长度的向量,时间改进为 178ms 与 69ms。日常操作没有惊天动地的差异,但速度稍快。
  • @thelatemail 感谢您运行测试。我会将mutate 列入我要记住的事项清单。
  • @thelatemail 我猜大部分(全部?)差异来自difflag 慢得多。
  • @eddi 是的,我们还没有在 C++ 中实现 lag()。如果您有数千万行,避免复制也可以节省大量时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 2014-10-07
  • 1970-01-01
  • 2012-07-25
相关资源
最近更新 更多