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

int*_*ern 3 loops r dataframe

嘿伙计,所以我有这个功能,从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)
}
Run Code Online (Sandbox Code Playgroud)

所以我想用这个函数做的是获取几个游戏ID的向量,并为每个游戏ID创建一个单独的数据框.例如:

gameids<- as.character(c(0021500580:0021500593))
Run Code Online (Sandbox Code Playgroud)

我想采用矢量"gameids",并创建十四个数据帧.如果有人知道我将如何做到这一点,将不胜感激!谢谢!

Abd*_*dou 6

您可以通过设置函数将data.frames保存到列表中,如下所示:

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)
Run Code Online (Sandbox Code Playgroud)

请注意,我无法对此进行测试,因为URL似乎无法正常工作.我收到以下连接错误:

Error in file(con, "r") : cannot open the connection
Run Code Online (Sandbox Code Playgroud)