如何在R中用pivot系列函数行计算多变量的RSE_Var
批量计算变量的相对标准误(RSE)
我有一个包含多个变量加权均值和加权标准误的数据集,示例数据集如下:
input.ds.wt <- tibble( id = c(1,2,3,4,5,6), wt.mean_vOne = c(1, 1, 1.3, 2.3, 1, 0), wt.mean_vTwo = rep(c(0.8,0.2), 3), wt.SE_vOne = c(0.1,0.01,0.2,0.02,0.3,0.03), wt.SE_vTwo = c(0.03,0.3,0.01,0.1,0.4,0.04) )
数据集输出:
> input.ds.wt # A tibble: 6 x 5 id wt.mean_vOne wt.mean_vTwo wt.SE_vOne wt.SE_vTwo <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 1 0.8 0.1 0.03 2 2 1 0.2 0.01 0.3 3 3 1.3 0.8 0.2 0.01 4 4 2.3 0.2 0.02 0.1 5 5 1 0.8 0.3 0.4 6 6 0 0.2 0.03 0.04
我需要为每一行批量计算每个变量的相对标准误(RSE),公式为:
RSE_vN = wt.SE_vN / wt.mean_vN
要求无需逐个指定变量名(vOne、vTwo……vN),每个变量都对应wt.mean_vN和wt.SE_vN列。
解决方案1:使用pivot_longer + pivot_wider转置计算
通过转置数据格式统一计算RSE,再转回宽格式,适合需要保留中间步骤的场景:
library(tidyverse) # 计算RSE并合并回原数据集 result <- input.ds.wt %>% # 将均值和标准误列转为长格式,提取变量标识 pivot_longer( cols = -id, names_to = c(".value", "var"), names_pattern = "wt\\.(mean|SE)_(.*)" ) %>% # 计算RSE mutate(RSE = SE / mean) %>% # 转回宽格式,生成带RSE的列 pivot_wider( id_cols = id, names_from = var, values_from = c(mean, SE, RSE), names_glue = "wt.{.value}_{var}" ) %>% # 合并原数据集,调整列顺序 left_join(input.ds.wt, by = "id") %>% select(id, starts_with("wt.mean"), starts_with("wt.SE"), starts_with("wt.RSE")) print(result)
解决方案2:使用dplyr::across直接批量计算
无需转置,直接遍历标准误列匹配对应均值列计算,更高效简洁:
library(tidyverse) # 直接批量计算RSE,添加至原数据集 result2 <- input.ds.wt %>% mutate( across( starts_with("wt.SE_"), ~ .x / get(str_replace(cur_column(), "SE", "mean")), .names = "wt.RSE_{str_remove(.col, 'wt.SE_')}" ) ) print(result2)
处理均值为0的特殊情况
如果存在均值为0的行,会得到Inf,可添加条件判断替换为NA:
result2 <- input.ds.wt %>% mutate( across( starts_with("wt.SE_"), ~ ifelse(get(str_replace(cur_column(), "SE", "mean")) == 0, NA_real_, .x / get(str_replace(cur_column(), "SE", "mean"))), .names = "wt.RSE_{str_remove(.col, 'wt.SE_')}" ) )
内容的提问来源于stack exchange,提问作者abrar
相关产品推荐
相关产品推荐

