简体   繁体   English

我如何 plot 列子集与另一列的平均值?

[英]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!!我会先说我是一个完整的 R 新手,并且被要求做一些超出我想象的计算,所以如果这不是问这个问题的正确方法,请提前原谅我!

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).我有一个 R 数据框,它有 2 列:一列是年龄 (18-80),另一列是具有三种可能结果 (0,1,2) 的因变量。 I would like to plot a graph that has x = age and y = the average of the dependent variable by age.我想 plot 一个图表,其中 x = 年龄和 y = 按年龄计算的因变量的平均值。 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.我知道如何制作一个简单的图表,并且我知道如何分别按年龄计算我的 (0,1,2) 列的平均值,但是对于从 18 到 80 的每个年龄然后手动执行此操作似乎真的很费力plot 在我想我必须制作的新数据框中对抗年龄。

How do I find the mean of my dependent variable by subset (age) and then plot it against age?如何通过子集(年龄)找到我的因变量的平均值,然后根据年龄找到 plot?

You could also do this with ggplot :您也可以使用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")

在此处输入图像描述

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

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