I have a date frame similar to the following toy data:
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"))
Where value
is some value of interest and year
and date
are self-explanatory. If I want to visually compare value
across years, having the different years in date
makes the graph not very helpful
library(tidyverse)
ggplot(df, aes(date, value, color = as.factor(year))) +
geom_line()
I can change the year in date
using lubridate
as follows, and this works
# This works
library(lubridate)
df2 <- df
year(df2$date) <- 2014
ggplot(df2, aes(date, value, color = as.factor(year))) +
geom_line()
But it would be helpful to change this as part of a dplyr
chain, something along the lines of
df3 <- df %>%
mutate(year(date) = 2014)
But that code returns an error
Error: unexpected '=' in: "df3 <- df %>% mutate(year(date) ="
Is there a way to make this work within a dplyr
chain, or do I just need to do this edit outside of the chain?