如何将日期格式(d.m.Y)更改为年(Y)&找到年度累计金额?

时间:2015-10-25 15:34:44

标签: r date format dplyr cumsum

我有一个2列数据帧x,如下所示。 “Publication.Date”列的格式为“%d。%m。%Y”。无论如何都要在“Publication.Date”中创建一个格式为“%Y”的新“年”列?

head(x,10)
   Publication.Date n
1        1979-09-05 1
2        1979-09-19 1
3        1980-03-19 1
4        1980-10-01 1
5        1980-12-10 1
6        1981-01-07 1
7        1981-04-02 1
8        1981-05-06 1
9        1981-11-18 1
10       1982-01-20 2

我尝试使用dplyr创建一个新的累积和列(如下所示),但实际上我想创建一个新的“年累积和,N”列,即通过逐个加“n”。

y <- mutate(x, N=cumsum(n))

head(y,10)
   Publication.Date n  N
1        1979-09-05 1  1
2        1979-09-19 1  2
3        1980-03-19 1  3
4        1980-10-01 1  4
5        1980-12-10 1  5
6        1981-01-07 1  6
7        1981-04-02 1  7
8        1981-05-06 1  8
9        1981-11-18 1  9
10       1982-01-20 2 11

我希望的结果如下。感谢您的任何建议。感谢。

         Year  n  N
1        1979  2  2
3        1980  3  5
6        1981  4  9
10       1982  2 11

2 个答案:

答案 0 :(得分:2)

您可以手动执行此操作,但我会从year获取data.table功能,只需直接在原始数据集x

上执行此操作
library(data.table)
x %>%
  group_by(Year = year(Publication.Date)) %>%
  tally() %>%
  mutate(N = cumsum(n))

# Source: local data frame [4 x 3]
# 
#    Year     n     N
#   (int) (int) (int)
# 1  1979     2     2
# 2  1980     3     5
# 3  1981     4     9
# 4  1982     2    11

虽然我不会先计算n先验

x %>%
  count(Year = year(Publication.Date)) %>%
  mutate(N = cumsum(n))
# Source: local data frame [4 x 3]
# 
#    Year     n     N
#   (int) (int) (int)
# 1  1979     2     2
# 2  1980     3     5
# 3  1981     4     9
# 4  1982     1    10

但是这并没有完全匹配您想要的输出,因为您预先设定n而没有实际提供完整数据,但这种方法对我来说似乎更好。

答案 1 :(得分:1)

我们可以提取“年”&#39;使用正则表达式,将其分组并使用summarise来获得所需的输出。从&#39; y开始来自OP的帖子

y %>% 
   group_by(Year= sub('-.*', '', Publication.Date)) %>%
   summarise(n= sum(n), N= last(N))
#    Year     n     N
#   (chr) (int) (int)
#1  1979     2     2
#2  1980     3     5
#3  1981     4     9
#4  1982     2    11

或者使用year中的library(lubridate)来提取“年”&#39;并使用summarise

library(lubridate)
y %>% 
   group_by(Year = year(as.Date(Publication.Date))) %>% 
   summarise(n= sum(n), N= last(N))
#    Year     n     N
#   (int) (int) (int)
#1  1979     2     2
#2  1980     3     5
#3  1981     4     9
#4  1982     2    11

如果我们使用data.table,我们会将初始数据集转换为&#39; data.table&#39; (setDT(x)按“&#39;年度”分组(使用year提取),获取“{1}}”&#39; n&#39;,创建新列& #39; N&#39;通过执行&#39; n&#39;的sum

cumsum