我是R的新手很抱歉,如果这个问题很愚蠢,但我环顾四周却无法找到答案:
我有一个面板数据集,包含24个月内25家银行的贷款数据。在这里,我制作了一个简单的版本,有3个银行和3个期间:
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)
我想创建一个为每个银行保存ggplot对象的循环。我的目标是稍后在markdown文件中使用这些对象。我试试这个:
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=" "))
}
但这里有多个错误。我想得到的是一系列ggplot对象,名为“bank1_total_loans”,“bank2_total_loans”等,每个对象的银行名称为ggplot title。 有没有办法做到这一点?
答案 0 :(得分:0)
example <- c("All's well", "All's well that ends well")
您可以使用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=" "))
)
函数避免循环。
答案 1 :(得分:0)
library(ggplot2)
library(dplyr)
library(zoo)
将日期变量转换为Date类以进行正确的可视化。
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)
}
让我们看看它的运作情况:
bank1_total_loans <- ggplot_creater(df, "bank1")
bank1and3_total_loans <- ggplot_creater(df,c("bank1", "bank3"))