Welcome to R Square

用 R 获取 GitHub 上高赞项目

楚新元 / 2025-05-28


本文参考自《Python 编程:从入门到实践》(第三版)第 17 章 Python 代码,书中讲解了通过调用 GitHub API 获取 GitHub 上星标最多的 Python 项目。这里改用 R 语言实现上述需求,默认获取 GitHub 上星标最多的 R 项目,代码如下:

# 编写函数
github_welcome_repo = \(language = "r", stars = 200) {
  
  api_url = "https://api.github.com/search/repositories"
  
  api_url |> 
    paste0(
      "?q=language:", language, 
      "+sort:stars+stars:>", stars
    ) |> 
    httr::GET(
      httr::add_headers("Accept" = "application/vnd.github.v3+json")
    ) |> 
    httr::content(as = "text", encoding = "UTF-8") |> 
    jsonlite::fromJSON() |> 
    purrr::pluck("items") -> items
  
  result = data.frame(
    name = items$name,
    owner = items$owner$login,
    stars = items$stargazers_count,
    repo = items$html_url,
    summary = items$description
  )
  
  return(result)
  
}

# 生成结果
github_welcome_repo()

上面的函数默认获取星标 200 以上的 R 语言项目,生成的结果按照星标数降序排列,读者可以根据实际需要自行调整参数值。

注意:受 GitHub API 限制,生成的结果只有前 30 条信息。