1

我正在尝试编写一个 for 循环,该循环将采用邮政编码,对国会信息数据库进行 API 调用,然后仅解析出代表邮政编码的国会议员的政党。

问题是一些邮政编码有不止一个国会议员,而另一些则根本没有(我认为是数据库的错误)。这意味着我需要遍历原始拉取返回的计数,直到没有更多代表为止。

问题是代表每个邮政编码的国会议员人数不同。因此,我希望能够为每个新国会议员将新变量名写入我的数据框中。也就是说,如果有 2 位国会议员,我想写新的列名为“party.1”和“party.2”等。

到目前为止,我有这段代码,我觉得我已经很接近了,但我真的不知道下一步该做什么。谢谢大家的帮助!

编辑:我发现这种方式更容易,但我仍然没有得到我正在寻找的结果

library(rjson)
library(RCurl)

zips <- (c("10001","92037","90801", "94011")

test <- matrix(nrow=4,ncol=7)
temp <- NULL
tst <- NULL

for (i in 1:length(zips)) {
   for (n in length(temp$count)) {
       temp <- (fromJSON(getURL(paste('https://congress.api.sunlightfoundation.com/legislators/locate?zip=', 
                                 zips[i],'&apikey= 'INSERT YOUR API KEY', sep=""), .opts = list(ssl.verifypeer = FALSE))))
    tst <- try(temp$results[[n]]$party, silent=T)
      if(is(tst,"try-error"))
        test[i,n] <- NA
      else
        test[i,n] <- (temp$results[[n]]$party)
  }
}
4

1 回答 1

3
install.packages("rsunlight")
library("rsunlight")
zips <- c("10001","92037","90801", "94011")
out <- lapply(zips, function(z) cg_legislators(zip = z))
# results for some only
sapply(out, "[[", "count")
# peek at results for one zip code
head(out[[1]]$results[,1:4])

bioguide_id   birthday chamber                                                    contact_form
1     S000148 1950-11-23  senate         http://www.schumer.senate.gov/Contact/contact_chuck.cfm
2     N000002 1947-06-13   house https://jerroldnadler.house.gov/forms/writeyourrep/default.aspx
3     M000087 1946-02-19   house                   https://maloney.house.gov/contact-me/email-me
4     G000555 1966-12-09  senate                       http://www.gillibrand.senate.gov/contact/

您可以根据需要在 lapply 或 for 循环中更改以添加列等。

退出派对可能很简单lapply(zips, function(z) cg_legislators(zip = z)$results$party)

于 2015-03-07T01:01:17.313 回答