Using a loop to create multiple data frames in R -


hey guys have function returns data frame of json data nba stats website. function takes in game id of game , returns data frame of halftime box score 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) } 

so function take vector of several game id's , create separate data frame each one. example:

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

i want take vector "gameids", , create fourteen data frames. if knew how go doing appreciated! thanks!

you can save data.frames list setting function follows:

getstats<- function(games){    listofdfs <- list() #create list in intend save df's.    for(i in 1:length(games)){ #loop through numbers of id's instead of id's      #you going use games[i] instead of 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 dataframes list   }    return(listofdfs) #return list of dataframes. }  gameids<- as.character(c(0021500580:0021500593)) getstats(games = gameids) 

please note not test because urls not seem working properly. connection error below:

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

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

android - Keyboard hides my half of edit-text and button below it even in scroll view -