【问题标题】:API call using R使用 R 调用 API
【发布时间】:2018-05-06 00:09:16
【问题描述】:

我有一个dataset from of VINs registered in NYS。我已将此文件读入 R 并希望使用 NHTSA VIN API

假设文件如下所示:

VIN = c("5XYPKDA55KG446393", "5XYPHDA56KG443792", "5XYPGDA33KG432573") 
myear4 = c("2019", "2019", "2019") 
ZIP = = c("10562", "10923", "13642") 

df = data.frame(VIN,myear4,ZIP) 

我如何拥有 R:

  1. 为每一行创建一个 API 调用

https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/5XYPKDA55KG446393?format=csv&modelyear=2019

https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/5XYPHDA56KG443792?format=csv&modelyear=2019

https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/5XYPGDA33KG432573?format=csv&modelyear=2019

  1. 将结果组合在一起匹配

【问题讨论】:

  • 你有没有尝试过?你可能会做类似x<-lapply(sprintf("https://.../%s?format=csv&modelYear=%d",df$VIN,df$myear4), httr::GET) 然后do.call(rbind,lapply(x,read.csv,stringsAsFactors=F)) 的事情。
  • @hrbrmstr 我用什么代码来转义原始 VIN 数据?没有任何。发布者以 CSV 格式提供数据。我只是使用阅读器将文件带入 R.
  • @r2evans 我尝试了x<-lapply(sprintf("vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/…), httr::GET) do.call(rbind,lapply(x,read.csv,stringsAsFactors=F)) 并收到了错误消息do.call(rbind,lapply(x,read.csv,stringsAsFactors=F)) Error in read.table(file = file, header = header, sep = sep, quote = quote, : 'file' must be a character string or connection 对于新蜜蜂的问题,我很抱歉,但我还没有找到关于 SO 的答案

标签: r api


【解决方案1】:

我在下载器 pkg 上很幸运。它是基本 R 下载功能的轻包装,只需替换那些 URL 中会更改的部分。看起来您使用的不是 ZIP:

library(downloader)
for( i in 1:3){ 
  download.file( paste0("https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/",
                        VIN[i],"?format=csv&modelyear=",myear4[i]), 
                destfile=paste0("test_", i ,".csv"))}
#-------------------
trying URL 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/5XYPKDA55KG446393?format=csv&modelyear=2019'
Content type 'application/octet-stream' length 2352 bytes
==================================================
downloaded 2352 bytes

trying URL 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/5XYPHDA56KG443792?format=csv&modelyear=2019'
Content type 'application/octet-stream' length 2351 bytes
==================================================
downloaded 2351 bytes

trying URL 'https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/5XYPGDA33KG432573?format=csv&modelyear=2019'
Content type 'application/octet-stream' length 2349 bytes
==================================================
downloaded 2349 bytes

我不确定这些文件是否可以保证具有所有相同的列,但如果是,您可以将它们与read.csv 和 `do.call(rbind, ...) 一起读入 R。有很多关于该部分的问题和已回答的问题,并且不鼓励在 SO 上提出多部分问题,所以我认为我不应该继续。

【讨论】:

  • 很抱歉提出新问题。是的,所有文件都有相同的列。我应该在 SO 中搜索什么来找到绑定问题的答案?
  • 翻转A!我对此投了反对票???我认为你的问题应该从你迄今为止尝试过的开始。
  • 再次感谢 @42- 成功了:files <- list.files(pattern = '\\.csv') tables <- lapply(files, read.csv, header = TRUE) combined.df <- do.call(rbind , tables)
猜你喜欢
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多