Python df.to_dict(orient="list")的R等价实现方法咨询
实现Python
df.to_dict(orient="list") 的R等价方案 Python中df.to_dict(orient="list")会生成键为列名、值为对应列所有元素组成的列表的字典结构,对应的R实现无需转长/宽格式,直接对tibble按列构造命名列表,再用jsonlite::toJSON()转换即可。
具体代码示例
- 构造示例tibble:
library(tibble) library(jsonlite) # 示例数据 my_tibble <- tibble( user_id = c(101, 102, 103), username = c("Luna", "Leo", "Zoe"), score = c(85, 92, 78) )
- 生成对应结构的列表并转JSON:
# 用base R的lapply按列提取,生成命名列表 list_struct <- lapply(my_tibble, identity) # 转换为JSON(auto_unbox=FALSE确保列值以数组形式输出) json_output <- toJSON(list_struct, auto_unbox = FALSE) # 查看结果 cat(json_output)
输出的JSON结构与Pythondf.to_dict(orient="list")转JSON的结果完全一致:
{"user_id":[101,102,103],"username":["Luna","Leo","Zoe"],"score":[85,92,78]}
补充说明
- 若习惯使用
purrr包,可替换为map(my_tibble, identity),效果相同。 - 之前转宽格式出错是因为误解了目标结构:
orient="list"不需要调整数据的长/宽形态,只需保留原列的顺序和内容,将每列打包为数组即可。
内容的提问来源于stack exchange,提问作者Sarah
相关产品推荐
相关产品推荐

