0

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
mustafghan
  • 169
  • 4
  • 15
  • Possible duplicate of [Pass arguments to dplyr functions](https://stackoverflow.com/questions/27975124/pass-arguments-to-dplyr-functions) – Adam Sampson Jul 29 '19 at 19:36
  • You are having problems because `dplyr` uses non-standard evaluation. Please see other duplicate threads on how to make a function with dplyr. Example answer showing how to use NSE at: https://stackoverflow.com/a/50407633/8485287. – Adam Sampson Jul 29 '19 at 19:37
  • FYI: when searching for this topic the `!!` is commonly called `bang-bang`. – Adam Sampson Jul 29 '19 at 19:38
  • None of these worked for me. Still getting the same error. – mustafghan Aug 05 '19 at 15:15

0 Answers0