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

如何将dataframe `raw_df`逐行转换为list?目标输出`wished_list`

实现方法

方法一:基础R原生写法

最直接的方式就是先把value列转为列表,再用cat列给列表元素命名:

# 分步实现
wished_list <- as.list(raw_df$value)
names(wished_list) <- raw_df$cat

# 一行简洁写法
wished_list <- setNames(as.list(raw_df$value), raw_df$cat)

方法二:tidyverse工具链写法

如果你习惯用tidyverse系列包,可以用purrr里的deframe()函数,先把两列数据框转成命名向量,再转为列表:

library(purrr)
wished_list <- raw_df %>% 
  deframe() %>% 
  as.list()

验证结果:执行完任意一种方法后,用str(wished_list)查看结构,会得到和目标一致的命名列表:

> str(wished_list)
List of 3
 $ a: chr "high"
 $ b: chr "mid"
 $ c: chr "low"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 17:37:01