对于函数getdata(origin, destination, year, classification)
如果我们运行getdata("tha", "sgp", 2015, "hs07")
我们将只得到泰国和新加坡之间的双边贸易。
但我需要东盟国家的所有双边贸易。有什么办法吗?我尝试自己编写嵌套循环,但它不起作用。
我对r编程很陌生。我使用的代码是:
origins <- c("tha", "vnm", "mys", "idn")
destinations <- c("vnm","sgp")
for (origin in origins ) {
for (destination in destinations) {
getdata(origins, destinations, 2015, "hs07")
}
}
您使用的输入存在一些问题:
- 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
的列表,您需要做的就是使用 purrr
中的map_df
将它们绑定到一个列表中。
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>