Modify year column : 2008, 2009, 2010 ... becomes 2008, 9, 10...

In the following example, how do I obtain desired_year from year?

toy_data <- data.frame(
  year = 2008:2017,
  desired_year = c(2008, 9, 10:17)
)
year desired_year
2008 2008
2009 9
2010 10
2011 11
2012 12
2013 13
2014 14
2015 15
2016 16
2017 17

I'm assuming you want 2008 to be 2008 and all the other years to have just the later values so I would use case_when. This is only works if the date is an integer as in your reprex:

library(dplyr)

data <- toy_data %>% 
  mutate(extractedYear = case_when(year == 2008 ~ 2008,
                                   TRUE ~ year - 2000))

If the year in your actual data is in a date format you will need to add the following line of code and you may have to change the equation as the year may come through as something like 20200101:

library(dplyr)

data <- toy_data %>% 
  mutate(Year = as.integer(Year),
                  extractedYear = case_when(year == 2008 ~ 2008,
                                   TRUE ~ year - 2000))
1 Like

Many thanks! Just what I wanted :smiley:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.