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

如何在R中提取JSON文件的ID与对应分类名称并合并为数据表

方法1:基础R实现(无需额外安装依赖包)

直接提取两个字段后合并为数据框:

# 提取id字段
id_vec <- unlist(categories[["items"]]["id"])
# 提取分类名称title字段
title_vec <- unlist(lapply(categories[["items"]][["snippet"]], function(x) x[["title"]]))
# 合并为表格
category_table <- data.frame(
  id = id_vec,
  title = title_vec,
  stringsAsFactors = FALSE
)

如果需要把id转为数值型,可额外加一行:category_table$id <- as.integer(category_table$id)


方法2:tidyverse生态实现(代码更简洁易读)

借助purrr处理嵌套列表:

library(tidyverse)

category_table <- categories[["items"]] %>%
  as_tibble() %>%
  # 从snippet嵌套结构中提取title
  mutate(title = map_chr(snippet, ~ .x[["title"]])) %>%
  # 只保留需要的两列
  select(id, title)

运行以上任意一种方法得到的category_table就是你需要的id+分类名称两列的表格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:15:00