R语言中如何将带分组前缀的time/response列data frame转换为分组列表
数据转换需求说明
当前R环境中的待处理data frame采用「分组标识.指标标识」的列名规则,包含H1、E9、F12三个分组的配对时间、响应数据,实际结构示例:
H1.time H1.response E9.time E9.response F12.time F12.response 1: 0.0 0.00000000 0.0 0.00000000 0.0 0.00000000 2: 0.2 0.00142469 0.2 0.00826733 0.2 0.00703381 3: 0.4 -0.00418229 0.4 0.01416873 0.4 0.00863728 4: 0.6 0.00361758 0.6 0.00845066 0.6 0.00739067 5: 0.8 0.00281592 0.8 0.01258872 0.8 0.00786157 6: 1.0 -0.00293035 1.0 0.01097368 1.0 0.00679848
目标转换效果
- 输出结构为R原生列表,每个列表元素对应一个独立分组(H1/E9/F12)的数据
- 每个列表元素都是结构规整的data frame,列名统一为
time、response,分别承载对应分组的时间值、响应值
可直接复用的R实现方案
基础R版本(无额外包依赖)
# 替换为你实际的data frame变量名 df <- 你的原始数据框名 # 提取所有分组标识,去掉列名中.time/.response的固定后缀 group_list <- unique(sub("\\.(time|response)$", "", names(df))) # 遍历每个分组,提取对应列生成规整子数据框,组装为列表 res <- lapply(group_list, function(g) { data.frame( time = df[[paste0(g, ".time")]], response = df[[paste0(g, ".response")]] ) }) # 为列表元素匹配对应分组名,支持按分组名索引 names(res) <- group_list
tidyverse版本(代码简洁适配管道流)
library(tidyverse) # 替换为你实际的data frame变量名 df <- 你的原始数据框名 # 第一步:将宽表转换为带分组标识的长表结构 df_long <- df %>% pivot_longer( cols = everything(), names_sep = "\\.", names_to = c("group", ".value") ) # 第二步:按分组拆分,生成列名统一的子数据框列表 res <- df_long %>% group_split(group, .keep = FALSE) %>% set_names(unique(df_long$group))
内容的提问来源于stack exchange,提问作者Sophia
相关产品推荐
相关产品推荐

