R: sub setting a column based on two columns

I have a dataframe called mat.new. Here's how to generate this data:

      year <- rep(1980:2015, each = 365) 
      doy <- rep(1:365, times = 36)

      set.seed(125) 
      val <- sample(0:1, size = 365*36,replace = TRUE) 
      mat <- as.matrix(cbind(year,doy,val))
      mat <- as.data.frame(mat)
      mat <- mat %>% 
              mutate(doy1 = rep(1:730, times = 18))
      mat <- mat[,c(1:2,4,3)]

      set.seed(123) 
      mat1 <- apply(matrix(sample(c(230:365), replace = TRUE, size = 2L * 36L), nrow = 36L), 2L, sort)
      mat1 <- t(apply(mat1, 1, function(x) x[order(x)]))
      colnames(mat1) <- c("D1", "D2")
      mat1 <- cbind(year = 1980:2015, mat1)
      mat1 <- as.data.frame(mat1)

      mat1[1:6,3] <- 5:10

      mat1 <- mat1 %>%
                mutate(D2 = ifelse(D1 > D2, D2 + 365, D2))

      mat_new <- mat %>% 
                 left_join(mat1, by = "year") 

mat_new has six columns. Column 1 = year, Column 2: doy (365 days each year), column 3 = doy1 but goes from 1 till 730 ( 2 years) and repeats again from 1 to 730. Column 4 has some value (val), column 5 and 6 has a certain start (D1) and end doy (D2) of each year. If D2 > 365, this implies the end date was next year. For e.g. for 1980, the end date is 370 which is the 5th day of 1981,

I need to subset val for each year based on their respective start and end doy. For e.g for 1980, the val I need to subset should start from 233 of 1980 till 5th of 1981 (370 is the end date). I thought of first creating another column with true and false which I can then use to subet the val

      mat_new1 <- mat_new %>% 
                    mutate(group1 = ifelse(D2 <= 365, doy >= D1 & doy <= D2 , doy >= D1 & doy1 <= D2)) 

The above line should create another column group1 with TRUE and FALSE. If D2 <= 365 i.e. the end date falls within the same year, use the doy column to subset D1 till D2. However, if D2 is in the next year (D2 > 365), then use doy as start date and take the end date from doy1 column. The above function, however for 1980 (and other years) only puts TRUE starting the D1 but ends at 365 for 1980 instead of going to 5th Jan of 1981 (370 from doy1)

What am I doing wrong here?