You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中按Line和Sex分组提取指定时间数据并生成多个DataFrame

在R中按Line+Sex分组提取指定时间点数据并保存独立文件

原始数据示例

先构造一个匹配需求的示例数据集:

library(tibble)
raw_df <- tibble(
  Time = c(10, 11, 11, 10, 11, 11, 10, 11, 11),
  Survival = c(0.9, 0.85, 0.78, 0.92, 0.88, 0.75, 0.91, 0.82, 0.76),
  Line = rep(c("LineA", "LineB", "LineC"), c(3, 3, 3)),
  Sex = rep(c("Male", "Female", "Male"), each=3),
  Dose = c(0, 10, 20, 0, 10, 20, 0, 10, 20)
)

期望结果示例

以LineA_Male组为例,提取后得到的独立DataFrame仅包含Survival和Dose列:

LineA_Male_df <- tibble(
  Survival = c(0.85, 0.78),
  Dose = c(10, 20)
)

实现方法

下面提供两种主流实现方式,按需选择:

方法1:使用tidyverse工具链(dplyr + purrr)

适合习惯tidy语法的用户,代码简洁直观:

library(dplyr)
library(purrr)

# 1. 筛选Time=11的行,并保留核心列
filtered_data <- raw_df %>% 
  filter(Time == 11) %>%
  select(Survival, Dose, Line, Sex)

# 2. 按Line+Sex分组拆分数据,自动丢弃分组列并给每个分组命名
grouped_dfs <- filtered_data %>%
  group_by(Line, Sex) %>%
  group_split(.keep = FALSE) %>%
  set_names(
    filtered_data %>% 
      distinct(Line, Sex) %>% 
      mutate(group_name = paste(Line, Sex, sep = "_")) %>% 
      pull(group_name)
  )

# 3. 批量保存每个分组为CSV文件
walk2(grouped_dfs, names(grouped_dfs),
      ~write.csv(.x, file = paste0(.y, ".csv"), row.names = FALSE))

方法2:Base R实现

无需额外安装包,适合轻量需求:

# 1. 筛选Time=11的行,仅保留需要的列
filtered_data <- raw_df[raw_df$Time == 11, c("Survival", "Dose", "Line", "Sex")]

# 2. 生成分组标签并拆分数据
filtered_data$group_label <- paste(filtered_data$Line, filtered_data$Sex, sep = "_")
split_dfs <- split(filtered_data[, c("Survival", "Dose")], filtered_data$group_label)

# 3. 循环保存每个分组文件
for (group_name in names(split_dfs)) {
  write.csv(split_dfs[[group_name]], 
            file = paste0(group_name, ".csv"), 
            row.names = FALSE)
}

关键说明

  • 最终生成的文件名格式为[Line]_[Sex].csv(比如LineB_Female.csv),便于对应不同分组
  • row.names = FALSE避免保存时自动添加行号列,保证输出数据干净
  • 若需保存为Excel格式,可将write.csv替换为writexl::write_xlsx(需先安装writexl包)

内容的提问来源于stack exchange,提问作者K.W

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 19:30:28