I have the following Code:
Total.Grains <- psd.all.data %>%
filter(Commodity_Code %in% list_all[[3]][[1]]) %>%
mutate(Commodity_Code = "Total Grains") %>%
group_by(Commodity_Code,Country_Code,Country_Name,Market_Year,Calendar_Year,Month,Attribute_ID,Attribute_Description,Unit_ID,Unit_Description) %>%
summarise(Value = sum(Value)) %>%
bind_rows(psd.all.data,.)
#Here we will change the NA values to Total.Grains.
Total.Grains$Commodity_Description[is.na(Total.Grains$Commodity_Description)] <- "Total Grains"
The above code creates an aggregate for Total Grains based on specific commodity codes given in the list_all
I can run the second code to create another aggregate for Total Oilseeds
Total.Oilseeds <- psd.all.data %>%
filter(Commodity_Code %in% list_all[[4]][[1]]) %>%
mutate(Commodity_Code = "Total Oilseeds") %>%
group_by(Commodity_Code,Country_Code,Country_Name,Market_Year,Calendar_Year,Month,Attribute_ID,Attribute_Description,Unit_ID,Unit_Description) %>%
summarise(Value = sum(Value)) %>%
bind_rows(psd.all.data,.)
#Here we will change the NA values to Total.Oilseeds.
Total.Oilseeds$Commodity_Description[is.na(Total.Oilseeds$Commodity_Description)] <- "Total Oilseeds"
I tried creating the following function so that the aggregates can be done with various commodities without having to copy paste it. I have the following function & forloop.
Run.Aggregation<- function(Aggregate, Table)
{for (i in seq(3, 10, by=1)) {
Table <- psd.all.data %>%
filter(Commodity_Code %in% list_all[[i]][[1]]) %>%
mutate(Commodity_Code = Aggregate) %>%
group_by(Commodity_Code,Country_Code,Country_Name,Market_Year,Calendar_Year,Month,Attribute_ID,Attribute_Description,Unit_ID,Unit_Description) %>%
summarise(Value = sum(Value)) %>%
bind_rows(psd.all.data,.)
Table$Commodity_Description[is.na(Table$Commodity_Description)] <- Aggregate
}}
Run.Aggregation(Aggregate = "Total Grains", Table = Total.Grains)
Run.Aggregation(Aggregate = "Total Oilseeds" Table = Total.Oilseeds)
But I'm getting the following error. I feel like i'm either writing the function and the for loop incorrectly or trying to resolve it incorrectly.
Error: $ operator is invalid for atomic vectors