如何编辑此代码以在数据集中包含年龄组

时间:2019-01-14 13:18:32

标签: r ggplot2

我有一个数据集,其中包含年龄组,编号如下:

  • 8 = 14-19
  • 9 = 20-24

以此类推。

我正在尝试将四个年龄段划分为折线图。我知道我正在使用的代码部分需要一些我不知道的调整。

我正在RStudio中使用ggplot

我尝试更改此部分:

  depression %>%
  filter(age>=15 & age <= 34) ->
  depression

depression$agecat <- cut(depression$age, c(14,19,25,30,35),
                         labels = c(" Females 15 to 19",
                                    " Females 20 to 24",
                                    " Females 25 to 29"
                                    " Females 30 to 34")`

对此没有成功:

  depression %>%
  filter(age>=8 & age <= 11) ->
  depression

depression$agecat <- cut(depression$age, c(8,9,10,11),
                         labels = c(" Females 15 to 19",
                                    " Females 20 to 24",
                                    " Females 25 to 29"
                                    " Females 30 to 34")`

完整代码如下:

  library(ggplot2)
library(tidyverse)
library(reshape2)
library(ggpubr)


options(scipen=10000)

depression <- read.csv("depression 2.csv")
depression <- depression[depression$year>= 1990 & depression$year <= 2015,]


    depression %>%
  filter(age>=15 & age <= 34) ->
  depression

    depression$agecat <- cut(depression$age, c(14,19,25,30,35),
                         labels = c(" Females 15 to 19",
                                    " Females 20 to 24",
                                    " Females 25 to 29"
                                    " Females 30 to 34")
)
   depression %>% 
  filter(sex == 2)%>%
  group_by(year,agecat)%>%
  summarise(val = mean(val))%>%
  ggplot(aes(year, val, group = agecat, col = agecat))+
  geom_line()+
  theme_classic()

我已经知道问题出在以下部分:

filter(age>=15 & age <= 34) ->

depression$agecat <- cut(depression$age, c(14,19,25,30,35)

我正在尝试实现something like this(无法嵌入图像,所以抱怨格式)。

0 个答案:

没有答案