如何编写R函数将各数据集保存至全局环境且不被覆盖
解决NBA球队比赛数据爬取时的覆盖问题
你的问题核心是每次调用函数都把结果存到同一个全局变量team里,导致新数据覆盖旧数据。这里提供几种实用的修改方案:
方案1:函数返回数据,手动命名存储(推荐)
修改函数让它返回处理后的比赛数据,调用时手动赋值给不同变量,避免全局变量冲突:
library(rvest) schedule <- function(team){ team_url <- paste0("https://www.basketball-reference.com/teams/", team, "/2023_games.html") team_log <- team_url %>% read_html() %>% html_node('#div_games') %>% html_table() colnames(team_log) <- c("Game", "Date", "Start", "Blank1", "BoxScore", "Blank2", "Opponent", "Result", "OT", "For", "Against", "W", "L", "Streak", "Notes") team_log <- subset(team_log, !Game == "G") return(team_log) } # 调用并分别存储 BOS_log <- schedule("BOS") ATL_log <- schedule("ATL")
执行后,BOS_log和ATL_log会分别保存凯尔特人队和老鹰队的数据,不会互相覆盖。
方案2:自动以球队代码命名全局变量
如果希望函数自动在全局环境创建对应球队的变量,可以用assign()函数,把传入的球队代码作为变量名:
library(rvest) schedule <- function(team){ team_url <- paste0("https://www.basketball-reference.com/teams/", team, "/2023_games.html") team_log <- team_url %>% read_html() %>% html_node('#div_games') %>% html_table() colnames(team_log) <- c("Game", "Date", "Start", "Blank1", "BoxScore", "Blank2", "Opponent", "Result", "OT", "For", "Against", "W", "L", "Streak", "Notes") team_log <- subset(team_log, !Game == "G") # 以球队代码为变量名存入全局环境 assign(team, team_log, envir = .GlobalEnv) } # 调用后全局环境会生成BOS和ATL两个变量 schedule("BOS") schedule("ATL")
方案3:批量爬取并返回列表(适合多队场景)
如果需要爬取多个球队,推荐把所有数据存入一个列表,方便统一管理:
library(rvest) schedule <- function(team){ team_url <- paste0("https://www.basketball-reference.com/teams/", team, "/2023_games.html") team_log <- team_url %>% read_html() %>% html_node('#div_games') %>% html_table() colnames(team_log) <- c("Game", "Date", "Start", "Blank1", "BoxScore", "Blank2", "Opponent", "Result", "OT", "For", "Against", "W", "L", "Streak", "Notes") subset(team_log, !Game == "G") } # 定义要爬取的球队列表 teams <- c("BOS", "ATL") # 批量爬取,结果存入列表 all_team_logs <- lapply(teams, schedule) names(all_team_logs) <- teams # 访问单个球队数据:all_team_logs$BOS 或 all_team_logs[["ATL"]]
内容的提问来源于stack exchange,提问作者user12025050
相关产品推荐
相关产品推荐

