如何在R中编写函数对多个体重类别重复计算生长值?
针对多体重类别计算生长值的R语言实现指导
需求说明
作为R语言新手,需要编写函数对数据集内的多个体重类别计算生长值,体重类别数量由数据集的列数决定(通常1-12个),现有函数无法批量应用到多列,需解决批量计算问题。
待处理数据集
performance_param<- data.frame(start_month = c('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct', 'nov', 'dec'), days_in_month = c(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), wt_y_1 = c(0, 60, 105, 150, 178.1, 206.3, 234.4, 262.5,290.6, 318.8, 346.9, 375.0), wt_y_2 = c(403.1, 431.3, 459.4, 487.5, 500.0, 512.5, 525.0, 537.5, 550.0, 562.5, 575.0, 587.5), wt_p_1 = c(600.0, 612.5, 625.0, 637.5, 643.8, 650.0, 656.3, 662.5, 668.8, 675.0, 681.3, 687.5), wt_p_2 = c(693.8, 700, 706.3, 712.5, 715.6, 718.8, 721.9, 725.0, 728.1, 731.3, 734.4, 737.5), wt_p_3 = c(740.6, 743.8, 746.9, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0), wt_p_4 = c(750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0), wt_p_5 = c(750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0), wt_p_6 = c(750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0), wt_p_7 = c(750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0), wt_p_8 = c(750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0), wt_p_9 = c(750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0), wt_p_10 = c(750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0, 750.0))
现有函数
calc_growth <- function(wt, days_in_month){ growth = (wt - lag(wt , default = first(wt )))/days_in_month return(growth) }
解决方案
你的现有函数逻辑正确,但仅能处理单个向量,无法批量应用到多列。以下两种方法可实现批量计算:
方法1:使用dplyr批量处理(推荐,代码简洁易读)
dplyr的across()函数可对指定列批量应用函数,步骤如下:
- 安装并加载dplyr包(若未安装):
install.packages("dplyr") library(dplyr)
- 批量计算生长值并添加为新列:
performance_param_with_growth <- performance_param %>% mutate(across(starts_with("wt_"), ~calc_growth(., days_in_month), .names = "growth_{.col}"))
starts_with("wt_"):匹配所有以wt_开头的体重列.names = "growth_{.col}":自动命名新列,例如wt_y_1对应生成growth_wt_y_1
方法2:基础R循环(适合理解底层逻辑)
若不想使用dplyr,可通过循环遍历体重列实现:
# 获取所有体重列的索引 wt_cols <- grep("^wt_", names(performance_param)) # 遍历每一列计算生长值并添加到原数据集 for(col in wt_cols){ col_name <- names(performance_param)[col] growth_col_name <- paste0("growth_", col_name) performance_param[[growth_col_name]] <- calc_growth(performance_param[[col]], performance_param$days_in_month) }
验证结果
运行以下代码查看计算后的前6行数据:
head(performance_param_with_growth)
内容的提问来源于stack exchange,提问作者Cae.rich
相关产品推荐
相关产品推荐

