I hope you can see how the below is something like 90% the same as I previously posted, its just wrapped with a map function to do the operation for each of the inputs, which are the products to process in the same way.
library(tidyver)
ttl <- data.frame(
stringsAsFactors = FALSE,
check.names = FALSE,
Product = c("Product A",
"Product A","Product A","Product A","Product B",
"Product B","Product B","Product B"),
Type = c("Type A",
"Type B","Type C","Total","Type A","Type B",
"Type C","Total"),
`2012` = c(2709.918,
2008.885,5064.211,9783.014,1227.195,971.391,
3599.942,5798.528),
`2013` = c(3225.571,
2067.898,5150.199,10443.668,1297.668,792.976,
4113.281,6203.925),
`2014` = c(3487.596,
2148.958,5115.467,10752.021,1387.781,771.827,
4245.271,6404.879),
`2015` = c(3779.972,
2303.884,5245.154,11329.01,1500.451,692.246,
4370.139,6562.836)
)
prodsvec <- c('Product A',
'Product B')
purrr::map(
prodsvec,
~{
step1 <- ttl %>% filter(
Product== .x
)
r1 <- filter(step1,
Type=="Total")
r2 <- filter(step1,
Type=="Type A")
#we want to subtract r2 so
r2x <- mutate(r2,
across(where(is.numeric),
~.*-1))
bind_rows(r1,r2x) %>% summarise(across(where(is.numeric),
sum))
}) %>% set_names(prodsvec)