R语言循环调用API时如何传递不带引号的州缩写参数?
解决R语言API调用中stateId参数传递问题
你的核心问题是URL字符串没有正确解析变量states[i],原代码里的stateId=states[i]会被直接当成字符串发送给API,而不是替换成对应的州缩写值。下面是具体的修复方案:
修复思路
通过动态拼接URL,把states[i]的实际值(不带引号的州缩写)插入到请求地址的stateId参数位置,让API收到正确的参数格式(比如stateId=AL)。
方案一:用paste0拼接URL
这是R原生的字符串拼接方法,不需要额外安装包:
states <- c("AL","AR","AZ","CA","CO","CT") # 从已有的AK州数据开始初始化目标数据框 officials2022 <- officials for(i in seq_along(states)) { # 动态生成包含当前州缩写的URL url <- paste0( "http://api.votesmart.org/Officials.getByOfficeTypeState?", "key=xxx&officeTypeId=L&stateId=", states[i], "&o=JSON" ) temp_raw <- GET(url) my_content <- content(temp_raw, as = 'text') my_content2 <- fromJSON(my_content) temp_officials <- my_content2$candidate$candidate # 避免空数据框导致rbind出错 if(!is.null(temp_officials) && nrow(temp_officials) > 0) { officials2022 <- rbind(officials2022, temp_officials) } }
方案二:用glue包拼接(更直观)
glue包支持用大括号{}直接嵌入变量,代码可读性更高:
# 先安装并加载glue包 install.packages("glue") library(glue) states <- c("AL","AR","AZ","CA","CO","CT") officials2022 <- officials for(i in seq_along(states)) { # 用glue直接嵌入变量,自动解析states[i]的值 url <- glue( "http://api.votesmart.org/Officials.getByOfficeTypeState?", "key=xxx&officeTypeId=L&stateId={states[i]}&o=JSON" ) temp_raw <- GET(url) my_content <- content(temp_raw, as = 'text') my_content2 <- fromJSON(my_content) temp_officials <- my_content2$candidate$candidate if(!is.null(temp_officials) && nrow(temp_officials) > 0) { officials2022 <- rbind(officials2022, temp_officials) } }
额外优化点
- 用
seq_along(states)替代1:length(states):当states为空向量时,前者不会生成错误的序列(比如1:0),更安全。 - 加入空数据检查:防止某些州没有返回数据时,
rbind报错中断循环。
内容的提问来源于stack exchange,提问作者lynda powell
相关产品推荐
相关产品推荐

