1

I am new to R so sorry if the question is dumb, but I have looked around and can't find an answer:

I have a panel dataset with loan data for 25 banks over a period of 24 months. Here I make a simpler version with 3 banks and 3 periods:

bank<-c("bank1", "bank1", "bank1", "bank2", "bank2", "bank2",   "bank3", "bank3", "bank3")

date<-c("jan-2016", "feb-2016", "Mar-2016", "jan-2016", "feb-2016","Mar-2016", "jan-2016", "feb-2016", "Mar-2016")

tot_loans<-c(200000, 100000, 200000, 155000, 233000, 435000, 99000,   111000, 129000)

df<-data.frame(bank, date, tot_loans) 

I'd like to create a loop that saves ggplot objects for each bank. My goal is to use these objects later in a markdown file. I try this:

bank_list <- unique(df$bank)

 for (i in seq_along(bank_list)) { 
     paste(i, "total_loans", sep="_") <- df %>%
     group_by(date) %>%
     filter(bank==[[i]]) %>%
     ggplot(aes(x=date, y=loan_size)) +
          geom_line() +
          ggtitle(paste([[i]], "value of loans", sep=" "))
   }

But there are multiple errors here. What I would like to get is a series of ggplot objects called "bank1_total_loans", "bank2_total_loans" etc, and each of them has the bank name as ggplot title. Is there a way to do this?

Gianzen
  • 73
  • 4

2 Answers2

0
library(tidyverse)
library(ggplot2)
bank<-c("bank1", "bank1", "bank1", "bank2", "bank2", "bank2",   "bank3", "bank3", "bank3")

date<-c("jan-2016", "feb-2016", "Mar-2016", "jan-2016", "feb-2016","Mar-2016", "jan-2016", "feb-2016", "Mar-2016")

tot_loans<-c(200000, 100000, 200000, 155000, 233000, 435000, 99000,   111000, 129000)

df<-data.frame(bank, date, tot_loans) 


plot_list <- df %>%
  split(.[["bank"]]) %>%
  map(~ggplot(data = ., aes(x=date, y=tot_loans)) +
        geom_line() +
        ggtitle(paste(.[1,1], "value of loans", sep=" "))
      )

You can avoid loop with map function.

H. Yong
  • 151
  • 11
  • Just a tip: If you would like to understand how the family of `map` functions work, watch the course *Advanced R Programming* at Coursera.org. – And_R May 20 '17 at 08:36
0
library(ggplot2)

library(dplyr)

library(zoo)

Transforming date variable into Date class for proper visualisation.

df$date <- as.yearmon(as.character(df$date), "%b-%Y")
df$date <- as.Date(df$date)

ggplot_creater <- function(data, selector){
    m <- data %>% filter(bank %in% selector) %>%
    ggplot(aes(x=date, y=tot_loans, group=bank)) +
    theme_bw(base_size=14)+
    geom_line() +
    labs(x="Date", y="Total of Loans",
         title="Value of loans")+
    facet_wrap(~bank)
}

Let's see how well it works:

bank1_total_loans <- ggplot_creater(df, "bank1")
bank1and3_total_loans <- ggplot_creater(df,c("bank1", "bank3"))
And_R
  • 1,647
  • 3
  • 18
  • 32