在R中使用blsAPI获取2020年失业人数? [包括代码和图像]

时间:2020-04-14 17:03:49

标签: r api

我正在尝试从R中的blsAPI中提取2020年的失业人数。我目前正在从link中复制此示例。我将年底更改为2020年,但直到最近一年,我仍然只获得直到2016年的失业人数。

查看图片enter image description here

这是代码

   #Install needed libraries 
install.packages('rjson')
library(rjson)
install.packages('blsAPI')
library(blsAPI)
library(ggplot2)

## Pull the data via the API
payload <- list(
  'seriesid'=c('LAUCN360610000000004', 'LAUCN360610000000006'),
  'startyear'=2007,
  'endyear'=2020)
response <- blsAPI(payload, 2)
json <- fromJSON(response)

## Process results
apiDF <- function(data){
  df <- data.frame(year=character(),
                   period=character(),
                   periodName=character(),
                   value=character(),
                   stringsAsFactors=FALSE)

  i <- 0
  for(d in data){
    i <- i + 1
    df[i,] <- unlist(d)
  }
  return(df)
}
View(apiDF)

unemployed.df <- apiDF(json$Results$series[[1]]$data)
labor.force.df <- apiDF(json$Results$series[[2]]$data)

## Change value type from character to numeric
unemployed.df[,4] <- as.numeric(unemployed.df[,4])
labor.force.df[,4] <- as.numeric(labor.force.df[,4])

## Rename value prior to merging
names(unemployed.df)[4] <- 'unemployed'
names(labor.force.df)[4] <- 'labor.force'

## Merge data frames
df <- merge(unemployed.df, labor.force.df)

## Create date and unemployement rate
df$unemployment.rate <- df$unemployed / df$labor.force
df$date <- as.POSIXct(strptime(paste0('1',df$periodName,df$year), '%d%B%Y'))


## Beginning and end dates for the Great Recession (used in shaded area)
gr.start <- as.POSIXct(strptime('1December2007', '%d%B%Y'))
gr.end <- as.POSIXct(strptime('1June2009', '%d%B%Y'))

View(df)
##Plot out the data
ggplot(df) + geom_rect(aes(xmin = gr.start, xmax = gr.end, ymin = -Inf, ymax = Inf), alpha = 0.4, fill="#DDDDDD") + geom_line(aes(date, unemployment.rate*100)) + ylab('Percent of labor force')  + xlab('Great Recession shaded in gray') + ggtitle('Unemployment Rate for Manhattan, NY (Jan 2007 to Dec 2010)') + theme_bw()

MichiganData <- blsQCEW('Area', year='2017', quarter='1', area='26000')
View(MichiganData)

2 个答案:

答案 0 :(得分:0)

该软件包似乎有两个版本(版本1和版本2),您正在使用哪个版本?

版本1的每次查询年限为10年。

鉴于您的开始日期是2007年,而您获得的最近年份是2016年,则可能是您使用的是版本1。

在上面提供的链接中查看API基础知识

答案 1 :(得分:0)

@Jamie_B 所述,BLS API 有两个版本(1.0 和 2.0);后者要求您注册并获取一个 api 密钥,然后您可以使用它来更有效地查询。您的问题可能源于此,但对于质量保证检查,我建议使用名为 blscrapeR 的包装器 api,其功能与原始 BLS 开发项目非常相似。

我在使用 R 的同一个项目环境中利用这两个包并没有遇到太多问题,因为这两个包都有独特的功能。