简体   繁体   English

存储循环导致 R 中的 dataframe

[英]Storing loop results in a dataframe in R

I have code that a user kindly helped me with in this thread .我有一个用户在这个线程中帮助我的代码。 It does exactly what I want it to, except the results are not stored in a dataframe.它完全符合我的要求,只是结果没有存储在 dataframe 中。

## Setting up API Call 
base_string1 <- "https.api.companyname/jurisdiction="
base_string2 <- "&date="
end_string <- "api_token=XYZ"

## Specifying objects to loop over 
dates <- seq(as.Date("1990-01-01"), as.Date("2022-01-01"), by = "year")
dates <- paste(head(dates, -1), tail(dates-1, - 1), sep = ":")

countries<- paste0("eu_", c("fra", "ger"))

## Looping over 
map_dfr(dates, function(dates){
  map_dfr(states, function(countries){
    api_string <-  paste0(base_string1, countries, base_string2, dates, end_string)
    print(api_string)
    json <- jsonlite::fromJSON(api_string)
    data.frame("countries" = countries, 
               "dates" = dates, 
               "total_number" = json[["results"]]$total_number)
  })
})

This gives me这给了我

 countries                 dates total_number
1  eu_ger 1990-01-01:1990-12-31       2404
2  eu_fra 1990-01-01:1990-12-31       2056
3  eu_ger 1991-01-01:1991-12-31       3490
4  eu_fra 1991-01-01:1991-12-31       6070
5  eu_ger 1992-01-01:1992-12-31       7808
6  eu_fra 1992-01-01:1992-12-31       1904

Which is the information I want, but I'd like to store it in a dataframe that I can access.这是我想要的信息,但我想将其存储在我可以访问的 dataframe 中。 I'd also like to call the countries "Germany" and France," and rather than the date range, I'd like to call it something like 1992 (and there's also a version where I go by month, in which case I'd like the value to be the year-month).我还想将这些国家/地区称为“德国”和“法国”,而不是日期范围,我想将其称为 1992 年之类的东西(还有一个版本,其中我按月为 go,在这种情况下我' d 希望值是年-月)。

I've tried adding the below after the API call, but without success.我尝试在 API 调用后添加以下内容,但没有成功。

json_df<- as_tibble(json)
json_df <- data.frame("countries" = countries, 
               "dates" = dates, 
               "total_number" = json[["results"]]$total_number)

How do I store the results in a dataframe, and ideally also change the country names/dates?如何将结果存储在 dataframe 中,并且最好还更改国家/地区名称/日期?

as suggested in the comments above try:按照上面评论中的建议尝试:

my_results <- map_dfr(dates, function(dates){
  map_dfr(states, function(countries){
    api_string <-  paste0(base_string1, countries, base_string2, dates, end_string)
    print(api_string)
    json <- jsonlite::fromJSON(api_string)
    data.frame("countries" = countries, 
               "dates" = dates, 
               "total_number" = json[["results"]]$total_number)
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM