R无法打开连接`

时间:2018-04-14 03:24:51

标签: r rjson

我正在从NBA.com API上搜索一些镜头数据。我正在使用的网址是

url = "stats.nba.com/stats/shotchartdetail?CFID=33&CFPARAMS=2017-18&ContextFilter=&ContextMeasure=FGA&DateFrom=&DateTo=&GameID=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerID=101107&PlusMinus=N&PlayerPosition=&Rank=N&RookieYear=&Season=2017-18&SeasonSegment=&SeasonType=Regular%20Season&TeamID=0&VsConference=&VsDivision="

通过复制和粘贴到您的浏览器,可以轻松验证此网站是否存在。但是,当我进入行

data = rjson::fromJSON(file = url)

我收到错误:文件错误(con," r"):无法打开连接... HTTP状态为' 403禁止'。

我尝试过将http和https添加到网址但无济于事。为什么R不读这个明显存在的网址?

1 个答案:

答案 0 :(得分:1)

概述

您需要将数据下载到,然后导入fromJSON()内的.json文件。我已经展示了如何提取列表对象marvin.williams.shot.data中包含的两个数据框:

  1. Marvin William个人2017-2018拍摄数据;和
  2. NBA联盟2017-2018赛季的平均投篮数据。
  3. 可重复的示例

    # load necessary packages
    library( jsonlite )
    
    # load necessary data
    download.file( url = "http://stats.nba.com/stats/shotchartdetail?CFID=33&CFPARAMS=2017-18&ContextFilter=&ContextMeasure=FGA&DateFrom=&DateTo=&GameID=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerID=101107&PlusMinus=N&PlayerPosition=&Rank=N&RookieYear=&Season=2017-18&SeasonSegment=&SeasonType=Regular%20Season&TeamID=0&VsConference=&VsDivision="
                   , destfile = "stats_nba.json" )
    
    # transfrom into data frame
    marvin.williams.shot.data <- 
      fromJSON( txt = "stats_nba.json" )
    
    # view results
    lapply( X = marvin.williams.shot.data, FUN = class)
    # $resource
    # [1] "character"
    # 
    # $parameters
    # [1] "list"
    # 
    # $resultSets
    # [1] "data.frame"
    
    # transfrom the matrix into a data frame
    player.shotchart.df <-
      as.data.frame( marvin.williams.shot.data$resultSets$rowSet[[1]]
                     , stringsAsFactors = FALSE )
    
    # assign colnames
    colnames( player.shotchart.df ) <-
      marvin.williams.shot.data$resultSets$headers[[1]]
    
    # view results
    dim( player.shotchart.df ) # [1] 563  24
    
    # transfrom the matrix into a data frame
    league.average.df <-
      as.data.frame( marvin.williams.shot.data$resultSets$rowSet[[2]]
                     , stringsAsFactors = FALSE )
    
    # assign colnames
    colnames( league.average.df ) <-
      marvin.williams.shot.data$resultSets$headers[[2]]
    
    # view results
    dim( league.average.df ) # [1] 20  7
    
    # end of script #