Another option using pivoting instead of iteration
library(tidyverse)
bloc_df <- data.frame(
Year = c(2011L,2011L,2011L,2011L,2011L,2011L,
2011L,2011L,2011L,2011L,2011L,2011L,2011L,2011L,2011L,
2011L,2011L,2011L,2010L,2010L,2010L,2010L,2010L,2010L,
2010L,2010L,2010L,2010L,2010L,2010L,2010L,2010L,2010L,
2010L,2010L,2010L),
TradeValue = c(663536,305249525,1370308420,2205006468,
40354718,18525637,1908591669,1395268,293072616,704938268,
11219301,12729123,1396866761,776401,66465942,2833496,
22148147,1750409643,674346,130382390,1040262882,906924506,
34583261,2140942,1824535234,1272176,173326030,638214736,
7639368,10267257,1131840170,816590,4195982,2104475,14299677,
1422877052),
Partner = as.factor(c("Antigua and Barbuda",
"Argentina","Brazil","Chile","Cuba","Dominica",
"Ecuador","Grenada","Honduras","Mexico",
"Nicaragua","Paraguay","Peru","Saint Kitts and Nevis",
"Saint Lucia","Saint Vincent and the Grenadines",
"Uruguay","Venezuela","Antigua and Barbuda","Argentina",
"Brazil","Chile","Cuba","Dominica","Ecuador",
"Grenada","Honduras","Mexico","Nicaragua","Paraguay",
"Peru","Saint Kitts and Nevis","Saint Lucia",
"Saint Vincent and the Grenadines","Uruguay",
"Venezuela"))
)
bloc_df %>%
mutate(`Pacific Alliance` = if_else(Partner %in% c("Mexico", "Colombia", "Peru", "Chile"), TRUE, FALSE),
`Andean Community` = if_else(Partner %in% c("Colombia", "Peru", "Ecuador", "Bolivia"), TRUE, FALSE)) %>%
pivot_longer(where(is.logical), names_to = "Bloc", values_to = "flag") %>%
filter(flag) %>%
group_by(Bloc, Year) %>%
summarise(TradeValue = sum(TradeValue))
#> `summarise()` has grouped output by 'Bloc'. You can override using the `.groups` argument.
#> # A tibble: 4 x 3
#> # Groups: Bloc [2]
#> Bloc Year TradeValue
#> <chr> <int> <dbl>
#> 1 Andean Community 2010 2956375404
#> 2 Andean Community 2011 3305458430
#> 3 Pacific Alliance 2010 2676979412
#> 4 Pacific Alliance 2011 4306811497
Created on 2021-06-28 by the reprex package (v2.0.0)