You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R为纽约州VIN数据集每行生成NHTSA VIN API调用?

Generating NHTSA VIN API Requests in R for Each Dataframe Row

Perfect question! To create the exact API request URLs you need for every row in your dataframe, you’ll use dynamic string interpolation to plug in each row’s VIN and model year values into the base NHTSA API endpoint. Here are two clean, practical approaches:

Base R Approach

If you prefer sticking to core R functions, paste0() lets you concatenate the URL parts directly:

# Add a new column with fully constructed API URLs
df$api_url <- paste0(
  "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/",
  df$VIN,
  "?format=csv&modelyear=",
  df$myear4
)

# Check the output
head(df$api_url)

This will generate a new api_url column where each entry matches the format you provided, tailored to the VIN and model year of that row.

dplyr + glue (More Readable Syntax)

For cleaner, more maintainable code, use dplyr for dataframe manipulation and glue for intuitive string interpolation:

First, install and load the required packages if you haven’t already:

install.packages(c("dplyr", "glue"))
library(dplyr)
library(glue)

Then build your API URLs with minimal fuss:

df <- df %>%
  mutate(api_url = glue(
    "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVinValues/{VIN}?format=csv&modelyear={myear4}"
  ))

The glue() function automatically pulls values from your dataframe columns using the names inside curly braces, making the code easy to read and adjust later.

Bonus: Fetching API Responses

Once you have the URLs, you can retrieve the decoded VIN data using purrr to iterate over each request:

install.packages("purrr")
library(purrr)
library(readr)

# Fetch CSV data from each API URL
api_responses <- map(df$api_url, ~read_csv(.x))

# Combine all responses into a single dataframe
decoded_data <- bind_rows(api_responses)

# Merge with your original dataframe if needed
final_dataset <- cbind(df, decoded_data)

Note: The NHTSA API has rate limits, so if you’re working with a large dataset, add a small delay between requests (e.g., Sys.sleep(1) inside the map call) to avoid being blocked.

内容的提问来源于stack exchange,提问作者Josh De La Rosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:32:13