如何根据列表名称移除列表的列表中NULL命名列表并生成合规DataFrame
解决NY Courts案件数据提取与合并问题
1. 正确过滤命名为NULL的列表元素
你之前的删除逻辑有误,列表的名称存储在names(tables)中,而非每个子表的$name属性。直接通过列表名称筛选即可去除无效的NULL命名元素:
# 加载依赖包 library(RCurl) library(XML) library(dplyr) library(purrr) library(rlist) # 获取网页表格数据 theurl <- getURL("https://nycourts.gov/reporter/slipidx/miscolo_2022_january.shtml", .opts = list(ssl.verifypeer = FALSE)) tables <- readHTMLTable(theurl) # 过滤名称为NULL的列表项(不依赖索引,复用性强) tables_filtered <- tables[names(tables) != "NULL"]
2. 标准化表结构并合并
网页中部分表格可能存在列名不统一的情况,先标准化为你需要的四列,再合并才能避免数据混乱:
# 定义标准化函数:确保每个有效表都有指定四列 standardize_table <- function(df) { # 目标网页的有效案件表都是4列结构 if (ncol(df) == 4) { colnames(df) <- c("title", "court", "date", "Slip Op No") return(df) } else { # 过滤掉列数不符的无效表 return(NULL) } } # 批量标准化表格并清理空值 tables_standardized <- tables_filtered %>% map(standardize_table) %>% list.clean(fun = is.null, recursive = FALSE) # 合并所有有效表格为最终DataFrame final_df <- bind_rows(tables_standardized)
验证输出
查看结果结构确认数据正确性:
# 查看DataFrame结构 str(final_df) # 查看前几行数据 head(final_df)
内容的提问来源于stack exchange,提问作者user17661126
相关产品推荐
相关产品推荐

