R语言 函数正在覆盖df而不是展开它

h9a6wy2h  于 2023-02-06  发布在  其他
关注(0)|答案(3)|浏览(113)

我是函数新手,所以我不知道如何处理代码,以便能够不断扩展输出df * out_df *,而不是在x上的每个值运行时覆盖它,在本例中,x是 Dataframe * country * 中的每个国家。最后的输出也只有关于巴西的信息。
下面是函数

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)
  
}

多谢了!

qyswt5oh

qyswt5oh1#

如果将Consumer添加为另一个分组变量,则应该能够完全避免循环:

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")
txu3uszq

txu3uszq2#

试试这个

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

7fyelxc53#

或者这个

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

相关问题