[英]Creating for loop using tq_get function from the tidyquant library to get unemployment filings by state in R? [Image & Code Included]
Goal: I want to get initial unemployment filings by state in a table for every state in the US目标:我想在美国每个 state 的表格中获得 state 的初始失业申请
Here is the example I am following: Link这是我正在关注的示例: 链接
Here is a quick snippet of the code from that link:以下是该链接中代码的快速片段:
ga_claims <-
"GAICLAIMS" %>%
tq_get(get = "economic.data",
from = "1999-01-01") %>%
rename(claims = price)
That first filter is for Georgia.第一个过滤器适用于格鲁吉亚。 However, I want it for all states .
但是,我希望它适用于所有州。 I was able to create a csv file to concatenate all state abbreviations with the 'ICLAIMS'.
我能够创建一个 csv 文件以将所有 state 缩写与“ICLAIMS”连接起来。 I simply want to pass a for loop through my function you see below.
我只是想通过我的 function 传递一个 for 循环,如下所示。 Attached is a screenshot of the csv I uploaded that has all the states with in that format...'CAICLAIMS', 'NYICLAIMS', 'ALICLAIMS' and so on...
附件是我上传的 csv 的屏幕截图,其中包含该格式的所有状态......'CAICLAIMS','NYICLAIMS','ALICLAIMS'等等......
We can create a function:我们可以创建一个 function:
library(dplyr)
library(tidyquant)
get_data <- function(x) {
x %>%
tq_get(get = "economic.data",from = "1999-01-01") %>%
rename(claims = price)
}
and pass each Claim_Code
through lapply
.并通过
lapply
Claim_Code
lapply(df$Claim_Code, get_data)
If you want to combine this into one dataframe, we can do:如果您想将其合并为一个 dataframe,我们可以这样做:
do.call(rbind, Map(cbind, lapply(df$Claim_Code, get_data),
Claim_Code = df$Claim_Code))
# date claims Claim_Code
#1 1999-01-02 9674 GAICLAIMS
#2 1999-01-09 19455 GAICLAIMS
#3 1999-01-16 20506 GAICLAIMS
#4 1999-01-23 12932 GAICLAIMS
#5 1999-01-30 10871 GAICLAIMS
#6 1999-02-06 7997 GAICLAIMS
OR using purrr
.或使用
purrr
。
library(purrr)
map2_df(map(df$Claim_Code, get_data), df$Claim_Code, cbind)
data数据
df <- data.frame(Claim_Code = c('GAICLAIMS', 'ALICLAIMS', 'AZICLAIMS'),
stringsAsFactors = FALSE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.