使用 lubridate 在 dplyr 链中编辑年份

Use lubridate to edit year within dplyr chain

我有一个类似于以下玩具数据的日期框:

df <- structure(list(year = c(2014, 2014, 2014, 2014, 2014, 2015, 2015, 
    2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016), date = structure(c(16229, 
    16236, 16243, 16250, 16257, 16600, 16607, 16614, 16621, 16628, 
    16964, 16971, 16978, 16985, 16992), class = "Date"), value = c(0.27, 
    0.37, 0.57, 0.91, 0.2, 0.9, 0.94, 0.66, 0.63, 0.06, 0.21, 0.18, 
    0.69, 0.38, 0.77)), .Names = c("year", "date", "value"), row.names = c(NA, 
    -15L), class = c("tbl_df", "tbl", "data.frame"))

其中 value 是一些感兴趣的值,yeardate 是不言自明的。如果我想直观地比较 value 跨年,date 中的不同年份会使图表不是很有用

library(tidyverse)    
ggplot(df, aes(date, value, color = as.factor(year))) +
  geom_line()

我可以按如下方式使用 lubridate 更改 date 中的年份,这很有效

# This works
library(lubridate)
df2 <- df

year(df2$date) <- 2014

ggplot(df2, aes(date, value, color = as.factor(year))) +
  geom_line() 

但是将其作为 dplyr 链的一部分进行更改会很有帮助,类似于

df3 <- df %>%
  mutate(year(date) = 2014)

但是那个代码returns一个错误

Error: unexpected '=' in: "df3 <- df %>% mutate(year(date) ="

有没有办法在 dplyr 链中进行这项工作,还是我只需要在链外进行此编辑?

df3 <- df %>%
  mutate(date=ymd(format(df$date, "2014-%m-%d")))
df3

# # A tibble: 15 x 3
#     year       date value
#    <dbl>     <date> <dbl>
#  1  2014 2014-06-08  0.27
#  2  2014 2014-06-15  0.37
#  3  2014 2014-06-22  0.57
#  4  2014 2014-06-29  0.91
#  5  2014 2014-07-06  0.20
#  6  2015 2014-06-14  0.90
#  7  2015 2014-06-21  0.94
#  8  2015 2014-06-28  0.66
#  9  2015 2014-07-05  0.63
# 10  2015 2014-07-12  0.06
# 11  2016 2014-06-12  0.21
# 12  2016 2014-06-19  0.18
# 13  2016 2014-06-26  0.69
# 14  2016 2014-07-03  0.38
# 15  2016 2014-07-10  0.77

all.equal(df2, df3)
# [1] TRUE

或使用do:

df4 <- df %>%
  do({year(.$date)<-2014; .})
df4
# same results as df3

all.equal(df2, df4)
# [1] TRUE

赋值只是另一个函数调用,所以你可以这样做:

mutate(df, date = `year<-`(date, 2014))

给出:

# A tibble: 15 x 3
    year       date value
   <dbl>     <date> <dbl>
 1  2014 2014-06-08  0.27
 2  2014 2014-06-15  0.37
 3  2014 2014-06-22  0.57
 4  2014 2014-06-29  0.91
 5  2014 2014-07-06  0.20
 6  2015 2014-06-14  0.90
 7  2015 2014-06-21  0.94
 8  2015 2014-06-28  0.66
 9  2015 2014-07-05  0.63
10  2015 2014-07-12  0.06
11  2016 2014-06-12  0.21
12  2016 2014-06-19  0.18
13  2016 2014-06-26  0.69
14  2016 2014-07-03  0.38
15  2016 2014-07-10  0.77