使用lubridate在dplyr链中编辑年份

13

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

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)

但是这段代码返回一个错误

错误: 在以下内容中有意外的“=”:"df3 <- df %>% mutate(year(date) ="

dplyr 链中是否有方法使其正常工作,还是我只需在链之外进行编辑?

2个回答

24

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

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

2
这是我个人认为更为优雅的写法,应该被采纳为解决方案。 - grssnbchr
似乎必须先加载库(即不能使用::)。例如, mutate(df, date = \lubridate::year<-`(date, 2014))` 会出错。 - MCornejo
1
@MCornejo,反引号包围的是函数名称,不包括包名。lubridate::\year<-`` - Axeman

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接