假设有一个数据框df,其中包含学生的年龄、性别和身高信息,可以按照以下步骤进行处理:

  1. 利用cut函数将年龄分段:
df$age_group <- cut(df$age, breaks = c(5, 10, 20, Inf), 
                     labels = c('5-10', '10-20', '>20'))
  1. 按照性别和年龄段进行分组统计身高的平均值:
library(dplyr)
df_summary <- df %>% group_by(sex, age_group) %>% 
              summarize(avg_height = mean(height))
  1. 用base包绘制折线图:
with(df_summary, plot(age_group, avg_height, type = 'l', 
                       lty = ifelse(sex == 'M', 1, 2), 
                       col = ifelse(sex == 'M', 'blue', 'red'),
                       xlab = 'Age Group', ylab = 'Average Height'))
legend('topleft', legend = c('Male', 'Female'), lty = c(1, 2), 
       col = c('blue', 'red'))

其中,lty参数控制线条类型,1代表实线,2代表虚线,col参数控制颜色,'blue'代表蓝色,'red'代表红色。legend函数用于添加图例。

R语言:按年龄段和性别分组统计身高变化并绘制折线图

原文地址: https://www.cveoy.top/t/topic/owip 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录