在R中按location分组将DataFrame转换为类Python字典的列表嵌套结构
在R中将DataFrame按分组转换为指定字典结构
问题背景
现有如下R数据框:
location <- c("a", "b", "c", "d", "e", "e") type <- c("city", "city", "town", "town", "village", "village") code <- c("123", "112", "83749", "83465", "38484757", "3838891") country <- c("zz", "zz", "zz", "zz", "zz", "zz") df <- data.frame(location, type, code, country)
需要按location分组,转换为如下结构的字典(R中对应命名列表):
{ 'a':[['city'],['123'],['zz']], 'b':[['city'],['112'],['zz']], 'c':[['town'],['83749'],['zz']], 'd':[['town'],['83465'],['zz']], 'e':[['village'],['38484757','3838891'],['zz']] }
此前尝试使用unclass+by的方法未得到预期结果:
unclass(by(df, df$location, function(x) { tmp <- x$code setNames(tmp, x$location[1]) tmp })) -> location_mapping
解决方案
方法1:Base R原生实现
利用split按location拆分数据框,再通过lapply遍历每个分组构造目标结构:
# 按location分组处理 location_mapping <- lapply(split(df, df$location), function(group) { # 构造每个分组的嵌套列表结构:[[type], [code], [country]] list( list(unique(group$type)), # 同一location的type唯一,用unique去重 list(group$code), # 保留该location下所有code值 list(unique(group$country))# 同一location的country唯一,用unique去重 ) })
查看结果结构:
str(location_mapping)
输出示例:
List of 5 $ a:List of 3 ..$ :List of 1 .. ..$ : chr "city" ..$ :List of 1 .. ..$ : chr "123" ..$ :List of 1 .. ..$ : chr "zz" $ b:List of 3 ..$ :List of 1 .. ..$ : chr "city" ..$ :List of 1 .. ..$ : chr "112" ..$ :List of 1 .. ..$ : chr "zz" # 其余分组结构类似,省略
方法2:输出为JSON格式(匹配预期可视化效果)
如果需要得到和示例完全一致的JSON格式输出,可使用jsonlite包:
# 首次使用需安装包 # install.packages("jsonlite") library(jsonlite) # 转换为带格式的JSON并打印 cat(toJSON(location_mapping, pretty = TRUE))
输出结果:
{ "a": [["city"], ["123"], ["zz"]], "b": [["city"], ["112"], ["zz"]], "c": [["town"], ["83749"], ["zz"]], "d": [["town"], ["83465"], ["zz"]], "e": [["village"], ["38484757", "3838891"], ["zz"]] }
问题说明
你之前的代码仅提取了code列,未处理type和country字段,也未构造多层嵌套列表的目标结构。上述方法通过遍历每个分组,分别处理三类字段并嵌套成列表,最终得到符合需求的结构。
内容的提问来源于stack exchange,提问作者blackfury
相关产品推荐
相关产品推荐

