Home > Enterprise >  function is overwriting df instead of expanding it
function is overwriting df instead of expanding it

Time:02-02

I am new to functions, so I am not sure how can I work around the code to be able to keep expanding my output df out_df, instead of overwriting it when it runs for each value on x, which in this case would be each country of the data frame country. My output at the end only has also only the information about Brazil.

Here is the function

consume_country_year <- function(x) {
  consume <- filter(data1, Consumer %in% x)%>%
    filter(year %in% c('2014', '2015', '2016'))%>%
    group_by(year)%>%
    summarise(Value=sum(Value))
    
  return(consume)
}

country <- c("China", "Germany", "USA", "Brazil")

for (x in country) {
  out_df <- consume_country_year(x)
  
}

Thanks a lot!

CodePudding user response:

You should be able to avoid looping entirely if you instead add Consumer as another grouping variable:

library(dplyr)

data1 %>%
  filter(
    Consumer %in% c("China", "Germany", "USA", "Brazil"),
    year %in% c('2014', '2015', '2016')
  ) %>%
  group_by(Consumer, year) %>%
  summarise(Value=sum(Value), .groups = "drop")

CodePudding user response:

Try this

out.list <- list()
for (i in seq_along(country) {
   out.list[[i]] <- consume_country_year(country[i])
}
out.df <- dplyr::bind_rows(out.list)

CodePudding user response:

Or this

for (x in country) {
  out_df <- dplyr::bind_rows(get0("out_df"),consume_country_year(x))
  
}
  • Related