здесь возможно решение с группировкой.Если вам нужен более общий подход, просто скажите мне.
library(tidyverse)
# the product types
product_index <- c('Apple', 'Pear', 'Banana', 'Orange')
# the reporters
reporter_index <- c('Spain', 'France', 'Italy')
## sample product data ----
dataList <- list(
apple_2015 = tibble(
Product = 'Apple',
Reporter = reporter_index,
Total_trade = c(100, 200, 300)
),
pear_2015 = tibble(
Product = 'Pear',
Reporter = reporter_index,
Total_trade = c(400, 500, 600)
),
banana_2015 = tibble(
Product = 'Banana',
Reporter = reporter_index,
Total_trade = c(100, 150, 600)
),
orange_2015 = tibble(
Product = 'Orange',
Reporter = reporter_index,
Total_trade = c(400, 500, 600)
),
apple_2016 = tibble(
Product = 'Apple',
Reporter = reporter_index,
Total_trade = c(200, 250, 300)
),
pear_2016 = tibble(
Product = 'Pear',
Reporter = reporter_index,
Total_trade = c(300, 500, 600)
),
banana_2016 = tibble(
Product = 'Banana',
Reporter = reporter_index,
Total_trade = c(200, 250, 300)
),
orange_2016 = tibble(
Product = 'Orange',
Reporter = reporter_index,
Total_trade = c(300, 500, 600)
)
)
## calculation ----
# create merged list, add year and bind rows into one large tibble
mergedDF <- lapply(1:length(dataList), function(i) {
dataList[[i]] %>%
mutate(Year = parse_number(names(dataList))[i])
}
) %>%
bind_rows() %>%
group_by(Year, Reporter)
# function with different combinations of products
resultsDF <- (function(){
tmpList <- mergedDF %>%
group_split()
lapply(1:length(tmpList), function(j) {
tmpDF <- tibble('Year' = unique(tmpList[[j]]$Year),
'Reporter' = unique(tmpList[[j]]$Reporter))
tmpDF[combn(tmpList[[j]]$Product, 2, function(i) paste0(i[1], i[2]))] <-
combn(tmpList[[j]]$Total_trade, 2, function(i) i[1] / i[2])
return(tmpDF)
}
) %>%
bind_rows()
})()