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

R网页抓取表格时如何编写IF条件处理随机变动的列名

R语言爬取动态表头表格解决方案

你只需要在原有代码的基础上增加列名判断逻辑,动态选择要处理的列即可,替换原有爬取得到output3之后的代码如下:

# 检测当前表格存在的房型列名
target_room_col <- if ("Accommodation Type" %in% colnames(output3)) {
  "Accommodation Type"
} else {
  "Room type"
}

# 执行字符串提取操作
output31 <- output3 %>% 
  mutate_at(c(target_room_col, "Price for 1 week"), ~str_extract(., ".*\n"))

如果需要后续数据处理更方便,可以将列名统一为固定值,避免后续逻辑中重复判断:

# 统一房型列的列名
colnames(output3)[colnames(output3) == target_room_col] <- "room_type"

如果你使用的是新版dplyr,推荐使用across替换已经被弃用的mutate_at语法,后续版本适配性更好:

output31 <- output3 %>% 
  mutate(across(c(target_room_col, "Price for 1 week"), ~str_extract(., ".*\n")))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:15:07