使用循环在R中创建多个数据帧 [英] Using a loop to create multiple data frames in R

查看:109
本文介绍了使用循环在R中创建多个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,所以我有这个功能,可以从NBA统计信息网站返回JSON数据的数据框.该函数获取特定游戏的游戏ID,并返回该游戏的半场得分的数据框.

Hey guys so I have this function that returns a data frame of JSON data from the NBA stats website. The function takes in the game ID of a certain game and returns a data frame of the halftime box score for that game.

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创建一个单独的数据帧.例如:

So what I would like to do with this function is take a vector of several game ID's and create a separate data frame for each one. For example:

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

我想取向量"gameids",并创建十四个数据帧.如果有人知道我将如何去做,将不胜感激!谢谢!

I would want to take the vector "gameids", and create fourteen data frames. If anyone knew how I would go about doing this it would be greatly appreciated! Thanks!

推荐答案

您可以通过如下设置功能将data.frames保存到列表中:

You can save your data.frames into a list by setting up the function as follows:

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)

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

Please note that I could not test this because the URLs do not seem to be working properly. I get the connection error below:

Error in file(con, "r") : cannot open the connection

这篇关于使用循环在R中创建多个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆