Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 views
in Technique[技术] by (71.8m points)

R-changing mean in aggregate function into percentage

i have a data that contains age and year(1991-2008)

i filtered my data that age gets 1 if<19 and 0 if > 19

database$age_cat[database$under19==1] <- "below 19 "
database$age_cat[database$under19==0] <- "above 19 "
percentage <- aggregate(insured~age_cat+year,data = database,mean)
z <- ggplot(data = percentage, mapping =aes(x=year,y=insured,color=age_cat)) + geom_point()
z+ scale_color_manual(values=c("blue", "red"))

i want to show the change of the percentage of insured age groups <19 and >=19 over years and to show each dot in every year in a different colour. (to explain my self i need to show each percentage of each dot in every year ) i tried using ggplot but its showing the mean and not percentage any suggestions?

question from:https://stackoverflow.com/questions/65646629/r-changing-mean-in-aggregate-function-into-percentage

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm going to strongly recommend the tidyverse. Within that set of packages I would approach your problem like so:

library(tidyverse)

percent <-
database %>%
    mutate(age_cat = case_when(
        under_19 == 1 ~ "below 19",
        under_19 == 0 ~ "over 19")) %>%
    group_by(year, age_cat) %>%
    summarise(count_ = n()) %>%
    mutate(percent = count_/sum(count_))

percent %>%
    ggplot(aes(x = year, y = percent, color = age_cat)) +
    geom_point()

I am assuming that each row is an individual that you would like to count, and you want a summary of the percentage of rows in that year / age_cat grouping. You can also summarise by count_ = sum(insured). Take note that you may want to add the na.rm = TRUE argument to your sum(insured) if you anticipate and need to ignore NA rows.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...