如何生成A LIST OF数据集&图表和导出它们?

时间:2018-05-01 07:42:30

标签: r loops ggplot2 fwrite

这是数据集:

# dataset call DT
DT <- data.table(
Store = rep(c("store_A","store_B","store_C","store_D","store_E"),4),
Amount = sample(1000,20))

我有两个目标必须实现:

  • 1.生成独立分组数据集,用于导出 EXCEL.CSV 文件。
  • 2.生成 INDEPENDENT Graph ,用于导出 PNG 文件。

*无需在一次操作中同时运行。

约束: 我只能通过 ONE by ONE 基本操作来执行这些操作,例如:

# For dataset & CSV export
store_A <- DT %>% group_by(Store) %>% summarise(Total = sum(Amount))

fwrite(store_A,"PATH/store_A.csv")

store_B <- DT %>% group_by(Store) %>% summarise(Total = sum(Amount))

fwrite(store_B,"PATH/store_A.csv")
.....
# For graph :

Plt_A <- ggplot(store_A,aes(x = Store, y = Total)) + geom_point()

ggsave("PATH/Plt_A.png")

Plt_B <- ggplot(store_B,aes(x = Store, y = Total)) + geom_point()

ggsave("PATH/Plt_B.png")
.....

*'for - loops'编写的方法可以找到,但令人困惑的是  在生成图表时更有效率和工作量,  for loop vs lapply family -  由于真实数据集有超过<2> 100万行70列和10k组生成,因此对于循环可能会非常慢地运行并使R本身崩溃。 实际数据集中的瓶颈包含10k个“存储”组。

1 个答案:

答案 0 :(得分:1)

因为一切都需要循环:

require(tidyverse)
require(data.table)

setwd("Your working directory")

# dataset call DT
DT <- data.table(
  Store = rep(c("store_A","store_B","store_C","store_D","store_E"),4),
  Amount = sample(1000,20)) %>% 
  #Arrange by store and amount
  arrange(Store, Amount) %>% 
  #Nesting by store, thus the loop counter/index will go by store
  nest(-Store)

#Export CSVs by store
i <- 1
for (i in 1:nrow(DT)) {
    write.csv(DT$data[i], paste(DT$Store[i], "csv", sep = "."))
  }

#Export Graphs by store
i <- 1
for (i in 1:nrow(DT)) {
  Graph <- DT$data[i] %>% 
    as.data.frame() %>%
    ggplot(aes(Amount)) + geom_histogram()

  ggsave(Graph, file = paste0(DT$Store[i],".png"), width = 14, height = 10, units = "cm")

}