Angela Russell
Angela Russell

Reputation: 143

Create a new column based on date ranges of another column

I am trying to create a new column (fishing_year) from a range of dates from another column (date). Essentially I am trying to say, for example, when the date range is between '2019-04-01' ~ '2020-03-31' allocate 2019 in the new column. Can anyone please help me with the script needed? I have converted the date column to a date object and tried this script (below) in various forms but to no avail. In R my date output looks like this 2019-04-01, but when I export to csv it looks like this csv

fishing_year=gpr_df_R %>% 
mutate(fishing_year=case_when(date = ('2019-04-01' ~ '2020-03-31') ~"2019",('2020-04-01' ~ '2021-03-31')~"2020", ('2021-04-01' ~ '2022-03-31')~"2021",('2022-04-01' ~ '2023-03-31')~"2022",('2023-04-01' ~ '2024-03-31')~"2023"))

Upvotes: -2

Views: 38

Answers (1)

Mark
Mark

Reputation: 12558

Here's another way, using 's year() function:

library(tidyverse)

gpr_df_R |> 
  mutate(date = ymd(date),
         fishing_year = ifelse(month(date) < 4, year(date) - 1, year(date))) 

Output:

        date fishing_year
1 2019-04-01         2019

Upvotes: 0

Related Questions