Function
コメント・参照等
function (download_folder)
{
path_to_folder <- paste0("C:/Users/", Sys.info()["user"], download_folder)
setwd(path_to_folder)
lapply(c("Nippon"), require, character.only = T)
KokusaiShuushi <- list()
csv_files <- dir(path = path_to_folder, pattern = ".csv$")
for (iii in seq(csv_files)) {
buf0 <- read.csv(file = csv_files[iii], header = F, skip = 0, stringsAsFactor = F, check.names = F, fileEncoding = "cp932", na.strings = c(""))
buf1 <- buf0[!apply(buf0, 1, function(x) all(is.na(x))), ]
buf2 <- buf1[, !apply(buf1, 2, function(x) all(is.na(x)))]
sheet_unit <- gsub(".+単位.?(.+)\\)", "\\1", zen2han(buf2[5, 1]))
sheet_title <- gsub(".+\\.", "", zen2han(buf2[2, 1]))
buf3 <- buf2[!apply(buf2[, -c(1, 2)], 1, function(x) all(is.na(x))), ]
tmp0 <- apply(buf3, 1, function(x) gsub("NA|\\(.+\\)|\\s|[[:punct:]]|[a-z]", "", paste0(x, collapse = ""), ignore.case = T))
buf4 <- buf3[sapply(tmp0, function(x) x != ""), ]
tmp_row <- !is.na(as.numeric(gsub(",", "", buf4[, 5])))
df_colname <- buf4[!tmp_row, ]
df_value <- buf4[tmp_row, ]
for (rrr in tail(rev(seq(nrow(df_colname))), -1)) {
df_colname <- f_fill_cells_column_direction(df = df_colname, row = rrr, below_check = T)
}
colnames(df_value) <- apply(df_colname, 2, function(x) gsub(":*NA|:[a-z].+$|\\s|\\([^)]+\\)", "", paste0(x, collapse = ":"), ignore.case = T))
df_value[, 4] <- seq(as.Date(paste0(df_value[1, 3], "-", gsub("([0-9]+).+", "\\1", df_value[1, 2]), "-1")), by = "+1 month", length.out = nrow(df_value))
df_value <- df_value[, -c(1:3)]
colnames(df_value)[1] <- "Date"
df_value[, -1] <- apply(df_value[, -1], 2, function(x) as.numeric(gsub(",", "", x)))
row.names(df_value) <- NULL
colnames(df_value)[-1] <- sapply(paste0(sheet_title, ":", colnames(df_value)[-1], ":", sheet_unit), zen2han)
colnames(df_value)[-1] <- paste0("国際収支:", colnames(df_value)[-1])
KokusaiShuushi[[iii]] <- df_value
print(tail(KokusaiShuushi[[iii]][, c(1, 2, 3)]))
remove(sheet_title, sheet_unit, df_value)
}
return(KokusaiShuushi)
}