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

如何在R中将数据框的两列汇总为指定格式的命名列表

解决方案

Base R 最简方法

直接使用split()函数,这是实现该需求最直接的方式,自动按分组生成带名称的列表:

首先构造测试数据框(如果你的数据框已有名称,替换成自己的即可):

df <- data.frame(
  ColumnA = c("Sample1", "Sample1", "Sample1", "Sample2", "Sample2", "Sample3", "Sample3", "Sample3", "Sample3", "Sample3"),
  ColumnB = c("Mutation1", "Mutation2", "Mutation4", "Mutation2", "Mutation3", "Mutation1", "Mutation2", "Mutation3", "Mutation4", "Mutation5")
)

执行转换:

result_list <- split(df$ColumnB, df$ColumnA)

运行后输出的result_list就是你需要的格式。


Tidyverse 方法(适合习惯tidy语法的用户)

如果日常使用dplyr等tidyverse工具,可以用以下两种方式:

方式1:group_split + set_names

library(dplyr)
library(purrr)

result_list <- df %>%
  group_split(ColumnA, .keep = FALSE) %>%
  set_names(unique(df$ColumnA))

方式2:nest + deframe

library(tidyr)
library(dplyr)

result_list <- df %>%
  nest(data = ColumnB) %>%
  deframe()

以上两种方法都能生成符合要求的命名列表。

内容的提问来源于stack exchange,提问作者subject1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:35:45