如何用tidyverse转换R中含name/value对的嵌套列表
使用tidyverse转换嵌套列表格式
实现思路
借助purrr的列表遍历能力和dplyr的数据处理工具,批量将每个子列表中attributes字段的name/value对转换为直接的命名键值对,同时把字符串型的布尔值转为R原生逻辑值。
示例代码
首先构造输入的嵌套列表:
library(tidyverse) # 示例输入(包含多个目标子列表) input_list <- list( list( name = 'foo', type = 'bar', attributes= list( list(name='color', value='blue'), list(name='batch', value=123), list(name='is_available', value='true') ) ), list( name = 'baz', type = 'qux', attributes= list( list(name='size', value='large'), list(name='quantity', value=456), list(name='is_available', value='false') ) ) )
定义处理单个子列表的函数并批量应用:
# 单个子列表处理函数 process_single_item <- function(item) { # 转换attributes结构:name/value对转命名列表 cleaned_attrs <- item$attributes %>% map_dfr(~.) %>% # 将嵌套小列表转为数据框 mutate( # 转换字符串布尔值为R原生逻辑值 value = case_when( value == 'true' ~ TRUE, value == 'false' ~ FALSE, TRUE ~ value # 其他值保持原格式 ) ) %>% deframe() # 将数据框转为命名向量,再转成列表 # 替换原列表的attributes字段 item$attributes <- as.list(cleaned_attrs) item } # 批量处理所有子列表 output_list <- input_list %>% map(process_single_item)
转换后效果
处理后的output_list中,每个子列表的attributes结构变为目标格式,以第一个子列表为例:
list( name = 'foo', type = 'bar', attributes= list( color='blue', batch=123, is_available=TRUE ) )
内容的提问来源于stack exchange,提问作者Yuriy Barvinchenko
相关产品推荐
相关产品推荐

