简体   繁体   中英

How do I plot an average of a column subset against another column?

I will preface this by saying that I am a complete R novice and have been asked to do some calculations that are way over my head, so please forgive me in advance if this is not the right way to ask this question!!

I have an R data frame that has 2 columns: one is age (18-80) and the other is a dependent variable that has three possible outcomes (0,1,2). I would like to plot a graph that has x = age and y = the average of the dependent variable by age. I know how to make a simple graph and I know how to calculate the average of my (0,1,2) column by age individually, but it seems really labor-intensive to do that manually for every age from 18 to 80 and then plot that against age in a new data frame that I guess I'd have to make.

How do I find the mean of my dependent variable by subset (age) and then plot it against age?

You could also do this with ggplot :

dat <- data.frame(age=sample(18:80, 250, replace=TRUE), 
                  y = sample(0:2, 250, replace=TRUE))

ggplot(dat, aes(x=age, y=y)) + 
  stat_summary(fun.data = function(y)data.frame(y=mean(y)), 
               geom="line")

在此处输入图像描述

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