Function

コメント・参照等

FUN = f_read_GDP_of_Japan.r
function (download_folder) 
{
    lapply(c("Nippon"), require, character.only = T)
    path_to_folder <- paste0("C:/Users/", Sys.info()["user"], download_folder)
    setwd(path_to_folder)
    csv_files <- dir()
    sheet_titles_j <- sheet_titles_e <- sheet_unit <- vector()
    gdp_japan <- list()
    for (iii in seq(csv_files)) {
        tmp0 <- read.csv(file = csv_files[iii], header = T, skip = 0, stringsAsFactor = F, na.strings = c("", "***"), check.names = F, fileEncoding = "cp932")
        tmp1 <- f_remove_blank_row_and_column(df = tmp0)
        sheet_unit[iii] <- zen2han(tmp1[1, tail(which(!is.na(tmp1[1, ])), 1)])
        sheet_titles_j[iii] <- zen2han(tmp1[1, 1])
        sheet_titles_e[iii] <- tmp1[2, 1]
        first_date_row <- which(!is.na(as.numeric(substring(tmp1[, 1], 1, 4))))[1]
        buf <- gsub("\\s", "", tmp1[first_date_row, 1])
        first_year <- as.numeric(substring(buf, 1, 4))
        first_month <- as.numeric(substring(buf, 6, regexpr("-", buf) - 1))
        if (!grepl("暦年|前年比|年度|前年度比", tmp1[1, 1])) {
            date_column <- seq(as.Date(paste0(first_year, "-", first_month + 2, "-1")), by = "3 month", length.out = nrow(tmp1) - first_date_row + 1)
        }
        else {
            date_column <- seq(as.Date(paste0(first_year, "-", first_month, "-1")), by = "12 month", length.out = nrow(tmp1) - first_date_row + 1)
        }
        value_column <- tmp1[-c(1:(first_date_row - 1)), -1]
        datadf <- data.frame(date_column, value_column, stringsAsFactors = F)
        tmp2 <- f_fill_cells_column_direction(df = tmp1, row = 3, below_check = F)
        tmp3 <- f_fill_cells_column_direction(df = tmp2, row = 4, below_check = T)
        datadf_colnames <- paste0(sheet_titles_j[iii], ":", sapply(gsub(":na", "", paste0(tmp3[3, ], ":", tmp3[4, ], ":", tmp3[5, ]), ignore.case = T), zen2han))
        colnames(datadf) <- datadf_colnames
        colnames(datadf)[1] <- "Date"
        datadf[, -1] <- apply(datadf[, -1], 2, function(x) as.numeric(gsub(",", "", x)))
        datadf <- datadf[!apply(datadf[, -1], 1, function(x) all(is.na(x))), ]
        row.names(datadf) <- NULL
        print(iii)
        print(csv_files[iii])
        print(colnames(datadf)[2:3])
        print(sheet_unit[iii])
        print(tail(datadf[, c(1:2)]))
        cat("\n")
        colnames(datadf)[-1] <- paste0("国内総生産:", colnames(datadf)[-1])
        gdp_japan[[iii]] <- datadf
    }
    return_list <- list(gdp_japan = gdp_japan, sheet_titles_j = sheet_titles_j, sheet_titles_e = sheet_titles_e, sheet_unit = sheet_unit)
    return(return_list)
}