繁体   English   中英

功能分组和绘图? -R

[英]Function to group by and plot? - R

我是R的新手,并且正在DataQuest上R课程。 我有csv的森林大火。 该文件可以在这里下载:

https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/

我想创建一个按“ x”(例如,月或日)分组数据并返回计数的条形图的函数。

library(readr)
library(dplyr)
library(ggplot2)

forestFires <- read_csv("forestfires.csv")

forestFiresCountPlot <- function(x) {
  forestFiresGroup <- forestFires %>%
  group_by(x) %>% 
  summarise(n(x)) %>%
  ggplot(data = forestFiresGroup) + 
    aes(x = x, y = n(x)) +
    geom_bar()
}

forestFiresMonth <- forestFiresCountPlot(month)
forestFiresDay <- forestFiresCountPlot(day)

# Output - Error: Column `x` is unknown

当我调用该函数时,如何指出月份和日期是列?

欢迎使用dplyr / ggplot2 / tidyverse进入编程世界。 您将想在这里阅读更多有关细节的信息 ,但是以下内容将帮助您前进:

library(tidyverse)

df <- read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv")

plot_group <- function(df, grp) {
  grp_var <- enquo(grp)
  df %>%
    count(!! grp_var) %>%
    ggplot(aes(x = !!grp_var, y = n)) +
    geom_col()
}

plot_group(df, month)
plot_group(df, day)

注意:您可能想先重新调整monthday变量,以便它们按更期望的顺序绘制:

df <- df %>%
  mutate(
    month = fct_relevel(month, str_to_lower(month.abb)),
    day = fct_relevel(day, c("sun", "mon", "tue", "wed", "thu", "fri", "sat"))
  )

您可以尝试如下操作:

forestFiresCountPlot <- function(x) {

  forestFires %>%  
    group_by_at(x) %>% 
    summarize(n = n()) %>%
    ggplot() + 
      aes_string(x = x, y = “n”) +
      geom_bar(stat = "identity")
}

forestFiresCountPlot("month")
forestFiresCountPlot("day")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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