使用lubridate在dplyr链中编辑年份

Mee*_*Met 5 r lubridate dplyr

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

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"))
Run Code Online (Sandbox Code Playgroud)

哪些value是感兴趣的价值,year并且date是不言自明的.如果我想value在不同年份进行视觉比较,那么在不同的年份date会使图表不是很有帮助

library(tidyverse)    
ggplot(df, aes(date, value, color = as.factor(year))) +
  geom_line()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我可以改变当年date使用lubridate如下,这个工程

# This works
library(lubridate)
df2 <- df

year(df2$date) <- 2014

ggplot(df2, aes(date, value, color = as.factor(year))) +
  geom_line() 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是,将其作为dplyr链条的一部分进行更改会有所帮助

df3 <- df %>%
  mutate(year(date) = 2014)
Run Code Online (Sandbox Code Playgroud)

但该代码返回错误

错误:意外'='在:"df3 < - df%>%mutate(年(日期)="

有没有办法让这个工作在一个dplyr链中,或者我只需要在链外做这个编辑?

Axe*_*man 9

分配只是另一个函数调用,因此您可以执行以下操作:

mutate(df, date = `year<-`(date, 2014))
Run Code Online (Sandbox Code Playgroud)

给出:

# 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
Run Code Online (Sandbox Code Playgroud)

  • 恕我直言,这是更优雅的解决方案,应该是公认的解决方案。 (2认同)

Jas*_*ang 6

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
Run Code Online (Sandbox Code Playgroud)

或使用do:

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

all.equal(df2, df4)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)