Search code examples
jsonrapivin

rOpengov/mpg, looping through VIN numbers returns error vs single use?


I'm trying to loop through the fevehicle() function in the mpg package courtesy of:

https://github.com/rOpenGov/mpg

I've been trying to feed the function multiple vinids, even giving the function 5 seconds of rest between loops just in case, but I keep getting an HTTP error even though alone, the function works fine. Any ideas what it might be? Below is the code:

#using a loop
vin = c("19UUA86209A000532", "19UUA86239A021598", "19UUA8F20CA037748", "19UUA8F21CA008002", "19UUA8F21CA017878")
for (i in vin) {
  library(mpg)
  print(i)
  print(substr(i, 13, 17))
  q = substr(i, 13, 17)
  z = feVehicle(q)
  Sys.sleep(5)
  z = t(unlist(z))

}

or
#using lapply to see a difference
lapply(vin, feVehicle)

both throw the following error:

[1] "19UUA86209A000532"
[1] "00532"
failed to load HTTP resource
Error in t.default(unlist(z)) : argument is not a matrix
> lapply(vin, feVehicle)
failed to load HTTP resource
failed to load HTTP resource
failed to load HTTP resource
failed to load HTTP resource
failed to load HTTP resource    

But when I run it on just one at a time it works fine: mpg::feVehicle(00532)

Vehicle data:
                                    value
atvType                            Diesel
barrels08              16.616739130434784
barrelsA08                            0.0
c240Dscr                             NULL
c240bDscr                            NULL
charge120                             0.0
charge240                             0.0
charge240b                            0.0
city08                                 21
city08U                               0.0
cityA08                                 0
cityA08U                              0.0
city

Solution

  • It's because in your single example you gave a number but in the loop you used a character:

    #using a loop
    vin = c("19UUA86209A000532", "19UUA86239A021598", "19UUA8F20CA037748", "19UUA8F21CA008002", "19UUA8F21CA017878")
    for (i in vin) {
      library(mpg)
      print(i)
      print(substr(i, 13, 17))
      q = substr(i, 13, 17)
      z = feVehicle(as.numeric(q))
      Sys.sleep(5)
      z = t(unlist(z))
    
    }
    
    [1] "19UUA86209A000532"
    [1] "00532"
    [1] "19UUA86239A021598"
    [1] "21598"
    [1] "19UUA8F20CA037748"
    [1] "37748"
    [1] "19UUA8F21CA008002"
    [1] "08002"
    [1] "19UUA8F21CA017878"
    [1] "17878"