如何编写嵌套的for循环中OEC库的GetData功能?

问题描述 投票:0回答:1

对于功能getdata(origin, destination, year, classification) 如果我们运行getdata("tha", "sgp", 2015, "hs07")我们将获得泰国和新加坡之间只有双边贸易。

但我需要在东盟国家的所有双边贸易。反正有这样做吗?我试着写嵌套的for循环自己,但没有奏效。

我非常新的与R编程。我使用的代码是:

origins <- c("tha", "vnm", "mys", "idn")
destinations <- c("vnm","sgp")
for (origin in origins ) {
  for (destination in destinations) {
    getdata(origins, destinations, 2015, "hs07")
  }
}
r for-loop
1个回答
0
投票

这里是一些问题与您所使用的输入:

  • 1)是一些数据不可用,这将引发以下错误: stop("No data available. Try changing year or trade classification.")。它专门为发生和vnm它将停止getdata搜索;
  • 2)当您运行getdata,如果你想再说一遍,你必须重新启动R对话和我不知道为什么。

因此,这里的仅使用sgp数据(我已经改变了与vnm对订单的代码工作)的方法。

library(tidyverse)
library(oec)

origins <- c("tha", "vnm", "mys", "idn")
destinations <- c("sgp","vnm")



res <- lapply(origins, function(x){

  lapply(destinations[1], function(y) {
  out1 <- getdata(x, y, 2015, "hs07")
  out2 <- getdata(y, x, 2015, "hs07")
  })
})

这将导致与data.frame列表,所有你需要做的就是将它们绑定到使用map_dffrom purrr之一。

restult <- map_df(res, bind_rows)

这使:

## A tibble: 20,049 x 31
#    year origin_id destination_id origin_name destination_name id   
#   <dbl> <chr>     <chr>          <chr>       <chr>            <chr>
# 1  2015 sgp       tha            Singapore   Thailand         0102 
# 2  2015 sgp       tha            Singapore   Thailand         0102~
# 3  2015 sgp       tha            Singapore   Thailand         0106 
# 4  2015 sgp       tha            Singapore   Thailand         0106~
# 5  2015 sgp       tha            Singapore   Thailand         0106~
# 6  2015 sgp       tha            Singapore   Thailand         0106~
# 7  2015 sgp       tha            Singapore   Thailand         0106~
# 8  2015 sgp       tha            Singapore   Thailand         0202 
# 9  2015 sgp       tha            Singapore   Thailand         0202~
#10  2015 sgp       tha            Singapore   Thailand         0202~
## ... with 20,039 more rows, and 25 more variables: id_len <int>,
##   product_name <chr>, group_id <chr>, group_name <chr>,
##   export_val <dbl>, export_val_growth_pct_5 <dbl>,
##   export_val_growth_val_5 <dbl>, export_val_growth_pct <dbl>,
##   export_val_growth_val <dbl>, export_rca <dbl>, import_val <dbl>,
##   import_val_growth_pct <dbl>, import_val_growth_pct_5 <dbl>,
##   import_val_growth_val <dbl>, import_val_growth_val_5 <dbl>,
##   import_rca <dbl>, trade_exchange_val <dbl>, pci <dbl>,
##   pci_rank <dbl>, pci_rank_delta <dbl>, top_exporter_code <chr>,
##   top_importer_code <chr>, top_importer <chr>, top_exporter <chr>,
##   color <chr>
© www.soinside.com 2019 - 2024. All rights reserved.