简体   繁体   中英

How to write a function in r which plots data for each unique value?

Based on Vancouver crime data, I am trying to write a function which plots the number of crimes per neighbourhood for all types of crime.

Below is what I have done so far:

all_type <- unique(crime$TYPE)

plot_all <- function(x) {

  m <- filter(crime, YEAR %in% c(2003, 2019), TYPE == x) %>%
  ggplot(aes(x= fct_rev(fct_infreq(NEIGHBOURHOOD))))+
  geom_bar(stat = "count")+
  coord_flip()+
  ggtitle(paste("Crime type:", x, sep=" "))+
  labs(x=" ", y="Total incidents, 2003-2019")

  for (i in seq_along(x)){
    result <- {print(m)}
  }
return(result)

}

plot_all(all_type)

But this only returns the plot for the first listed type of crime, instead of returning separate plots for each type of crime.

There are some issues with the function as posted. In the code below I will separate the problem of plotting one graph from the problem of plotting all graphs. To each of these problems will correspond a function.

First of all, the data I am using can be downloaded with the following instructions, that can be found at RPubs by RStudio:

Crime Data from Vancouver Police Department by Arash Tavassoli (2018-11-05)

url <- "ftp://webftp.vancouver.ca/opendata/csv/crime_csv_all_years.zip"
temp <- tempfile()
download.file(url, temp)
crime <- read.csv(unz(temp, "crime_csv_all_years.csv"))
unlink(temp)

Now the graphics code.

library(dplyr)
library(tidyr)
library(forcats)
library(ggplot2)

plot_one <- function(x, crime) {
  m <- filter(crime, YEAR %in% c(2003, 2019), TYPE == x) %>%
    ggplot(aes(x = fct_rev(fct_infreq(NEIGHBOURHOOD)))) +
    geom_bar(stat = "count") +
    coord_flip() +
    ggtitle(paste("Crime type:", x, sep=" ")) +
    labs(x = " ", y = "Total incidents, 2003-2019")
  m
}

plot_all <- function(crimedata){
  all_type <- unique(crimedata[["TYPE"]])
  g_list <- lapply(all_type, plot_one, crime = crimedata)
  lapply(g_list, print)
  g_list
}

g_all <- plot_all(crime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM