在R中使用循环创建多个数据框

4
我有一个函数,从NBA统计网站返回一个JSON数据的数据框。该函数接受某个比赛的比赛ID,并返回该比赛中场的盒式得分数据框。请看以下代码:

getstats<- function(game=x){
  for(i in game){
    url<- paste("http://stats.nba.com/stats/boxscoretraditionalv2?EndPeriod=10&
                EndRange=14400&GameID=",i,"&RangeType=2&Season=2015-16&SeasonType=
                Regular+Season&StartPeriod=1&StartRange=0000",sep = "")
    json_data<- fromJSON(paste(readLines(url), collapse=""))
    df<- data.frame(json_data$resultSets[1, "rowSet"])
    names(df)<-unlist(json_data$resultSets[1,"headers"])
  }
  return(df)
}

我希望这个函数能够接受一个包含多个游戏ID的向量,并为每个ID创建一个单独的数据框。例如:

gameids<- as.character(c(0021500580:0021500593))

我想要获取向量“gameids”,并创建14个数据框。如果有人知道如何做到这一点,将不胜感激!谢谢!
3个回答

10
你可以通过以下方式设置函数,将数据框保存到列表中:

您可以通过以下方式设置函数,将数据框保存到列表中:

getstats<- function(games){

  listofdfs <- list() #Create a list in which you intend to save your df's.

  for(i in 1:length(games)){ #Loop through the numbers of ID's instead of the ID's

    #You are going to use games[i] instead of i to get the ID
    url<- paste("http://stats.nba.com/stats/boxscoretraditionalv2?EndPeriod=10&
                EndRange=14400&GameID=",games[i],"&RangeType=2&Season=2015-16&SeasonType=
                Regular+Season&StartPeriod=1&StartRange=0000",sep = "")
    json_data<- fromJSON(paste(readLines(url), collapse=""))
    df<- data.frame(json_data$resultSets[1, "rowSet"])
    names(df)<-unlist(json_data$resultSets[1,"headers"])
    listofdfs[[i]] <- df # save your dataframes into the list
  }

  return(listofdfs) #Return the list of dataframes.
}

gameids<- as.character(c(0021500580:0021500593))
getstats(games = gameids)
请注意,我无法进行测试,因为这些网址似乎不能正常工作。我收到了以下连接错误:
Error in file(con, "r") : cannot open the connection

1

补充Abdou的答案,您可以使用assign()函数创建动态数据框以保存每个gameID的结果。

for(i in 1:length(games)){ #Loop through the numbers of ID's instead of the ID's

#You are going to use games[i] instead of i to get the ID
url<- paste("http://stats.nba.com/stats/boxscoretraditionalv2?EndPeriod=10&
            EndRange=14400&GameID=",games[i],"&RangeType=2&Season=2015-16&SeasonType=
            Regular+Season&StartPeriod=1&StartRange=0000",sep = "")
json_data<- fromJSON(paste(readLines(url), collapse=""))
df<- data.frame(json_data$resultSets[1, "rowSet"])
names(df)<-unlist(json_data$resultSets[1,"headers"])

# create a data frame to hold results
assign(paste('X',i,sep=''),df)
}

assign函数将创建与游戏ID数量相同的数据框,它们将被标记为X1、X2、X3......Xn。希望这可以帮助。


1
fortunes::fortune(236):唯一应该使用赋值函数的人是那些完全理解为什么你永远不应该使用赋值函数的人。 - Uwe

1
使用lapply(或sapply)将函数应用于列表并将结果作为列表获取。因此,如果你获得了一个包含多个游戏ID的向量和一个执行所需操作的函数,则可以使用lapply获取数据框的列表(因为函数返回df)。
我无法测试您的代码(使用提供的函数出现错误),但类似以下代码应该可以工作:
library(RJSONIO)
gameids<- as.character(c(0021500580:0021500593))
df_list <- lapply(gameids, getstats)

getstats<- function(game=x){
        url<- paste0("http://stats.nba.com/stats/boxscoretraditionalv2?EndPeriod=10&EndRange=14400&GameID=",
                     game,
                     "&RangeType=2&Season=2015-16&SeasonType=Regular+Season&StartPeriod=1&StartRange=0000")
        json_data<- fromJSON(paste(readLines(url), collapse=""))
        df<- data.frame(json_data$resultSets[1, "rowSet"])
        names(df)<-unlist(json_data$resultSets[1,"headers"])
        return(df)
}

df_list将包含您在gameids中提供的每个Id的1个数据框。

只需再次使用lapply进行其他数据处理,包括将数据框保存到磁盘。

如果您需要处理大量数据,则data.table是一个不错的包。特别是rbindlist允许您将列表中包含的所有dt(=df)合并为一个单一的dt(split将执行相反的操作)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接