国際通貨基金(IMF)の外国直接投資(FDI)のデータを整理する。この文書では、データの読み込み、整形、および分析を行う。
# 全てのデータの削除
rm(list = ls())
# Load necessary library
library(readr)
# Import FDIdata
FDIdata <- read.csv("Data_raw/IMF_CDIS.csv")
# Drop variable v22
FDIdata <- subset(FDIdata, select = -c(X))
# Keep rows where indicatorname is "Inward Direct Investment Positions, Derived, US Dollars"
FDIdata <- subset(FDIdata, Indicator.Name == "Inward Direct Investment Positions, Derived, US Dollars")
# Drop indicatorname and indicatorcode columns
FDIdata <- subset(FDIdata, select = -c(Indicator.Name, Indicator.Code))
# Keep rows where attribute is "Value"
FDIdata <- subset(FDIdata, Attribute == "Value")
# Drop attribute column
FDIdata <- subset(FDIdata, select = -Attribute)
countrycode
パッケージを使って、IMFの国コードをISO3Cに変換する。# Load necessary library
library(countrycode)
# Rename countrycode to imfn
names(FDIdata)[names(FDIdata) == "Country.Code"] <- "imfn"
# Convert imfn to iso3c using countrycode package
FDIdata$countrycode <- countrycode(FDIdata$imfn, "imf", "iso3c")
# Rename counterpartcountrycode to imfn_partner
names(FDIdata)[names(FDIdata) == "Counterpart.Country.Code"] <- "imfn_partner"
# Convert imfn_partner to iso3c using countrycode package
FDIdata$countrycode_partner <- countrycode(FDIdata$imfn_partner, "imf", "iso3c")
# Rename country name
names(FDIdata)[names(FDIdata) == "Counterpart.Country.Name"] <- "countryname_partner"
names(FDIdata)[names(FDIdata) == "Country.Name"] <- "countryname"
# Drop rows where countrycode or countrycode_partner is empty
FDIdata = subset(FDIdata, countrycode_partner != "NA")
FDIdata = subset(FDIdata, countrycode != "NA")
# Reshape long
library(tidyr)
FDIdata_long <- pivot_longer(FDIdata, cols = starts_with("X"), names_to = "year", values_to = "FDI")
# remove "X" from year
FDIdata_long$year <- gsub("X", "", FDIdata_long$year)
# Convert year to numeric
FDIdata_long$year = as.numeric(FDIdata_long$year)
# Drop rows with FDI="NA"
FDIdata_long = subset(FDIdata_long, FDI != "")
# Convert FDI variables to numeric, forcing conversion
FDIdata_long$FDI <- as.numeric(as.character(FDIdata_long$FDI))
# Convert FDI to natural logarithm
FDIdata_long$lnFDIstock <- log(FDIdata_long$FDI)
# FDIdata_longをcsvファイルとして保存
write.csv(FDIdata_long, "Data_output/FDIdata_long.csv", row.names = FALSE)