Function

コメント・参照等
  • 消費者物価指数ファイル(総務省)を読み込み整形する関数

FUN = f_read_CPI_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(pattern = "\\.csv$")
    cpi_japan <- list()
    for (iii in seq(csv_files)) {
        buf0 <- read.csv(file = csv_files[iii], header = F, skip = 0, stringsAsFactor = F, check.names = F, na.strings = c(""), fileEncoding = "cp932")
        row_name <- grep("品目$", buf0[, 1])
        row_weight <- grep("万分比", buf0[, 1])
        colnames(buf0) <- sapply(paste0(buf0[row_name, ], "(ウエイト:", buf0[row_weight, ], ")"), zen2han)
        buf1 <- buf0[!is.na(as.numeric(buf0[, 1])), ]
        buf1[, 1] <- as.Date(paste0(substring(buf1[, 1], 1, 4), "-", substring(buf1[, 1], 5, 6), "-1"))
        buf1[, -1] <- apply(buf1[, -1], 2, as.numeric)
        colnames(buf1) <- paste0(gsub("-", ":", gsub("(.+)-[0-9]+\\.csv$", "\\1", csv_files[iii])), ":", colnames(buf1))
        colnames(buf1)[1] <- "Date"
        colnames(buf1)[-1] <- paste0("消費者物価指数:", colnames(buf1)[-1])
        cpi_japan[[iii]] <- buf1
        print(tail(cpi_japan[[iii]][, 1:2]))
    }
    return(cpi_japan)
}