Hi, here's what you can do.
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tidyr)
response.data <- data.frame(stringsAsFactors=FALSE,
ReferenceNumber = c("aaa", "aaa", "aaa", "eee", "eee", "eee", "eee",
"hhh",
"hhh",
"hhh",
"hhh"),
Sequence = c(2, 1, 3, 2, 1, 5, 3, 2, 5, 4, 5),
S.Year = c(2016, 2016, 2017, 2016, 2016, 2017, 2017, 2017, 2017,
2017,
2017))
response.data %>%
group_by(ReferenceNumber, S.Year) %>%
summarise(Max = max(Sequence)) %>%
pivot_wider(names_from = "S.Year", values_from = "Max") %>%
mutate(Total = pmax(`2016`, `2017`, na.rm = TRUE)) %>%
select(ReferenceNumber, Total, everything())
#> # A tibble: 3 x 4
#> # Groups: ReferenceNumber [3]
#> ReferenceNumber Total `2016` `2017`
#> <chr> <dbl> <dbl> <dbl>
#> 1 aaa 3 2 3
#> 2 eee 5 2 5
#> 3 hhh 5 NA 5
Created on 2019-12-16 by the reprex package (v0.3.0)
The changes are that you also group by S.Year and then pivot the data frame to a wider format using tidyr::pivot_wider. Then you can create the Total column by using pmax on 2016 and 2017
response.data %>%
group_by(ReferenceNumber, S.Year) %>%
summarise(Max = max(Sequence)) %>%
pivot_wider(names_from = "S.Year", values_from = "Max") %>%
mutate(Total = pmax(`2016`, `2017`, na.rm = TRUE)) %>%
select(ReferenceNumber, Total, everything())