R: 複数ファイルの読み込み, purrr ver. 2

purrrは関数でプログラムを書くためのパッケージです。

purrrでどのようなことができるかを学びます。

 

I.複数ファイルの読み込み

 

1.別々のファイルとして読み込む

 

Getting started with the purrr package in R

 

 

2.一つにまとめて読み込む

 

Reading and combining many tidy data files in R

 

3つのファイルを一つにまとめます。サンプルは別企業の株価ですからまとめても仕方がないものですが、同一企業の毎日のデータが別ファイルになっている場合には役立ちます。

 

 

3.スクリプト

 

# import librries
library(tidyverse)
library(purrr)
# set working directory
setwd("data/stocks")
getwd()
# read the data
URL <- "http://static.lib.virginia.edu/statlab/materials/data/stocks.zip"
download.file(url = URL, destfile = basename(URL))
unzip(basename(URL))
# get all files ending in csv
files <- list.files(pattern = "csv$") 
# read in data
dat2 <- map(files, read.csv)
names(dat2) <- gsub("\\.csv", "", files)
dat2

# read three files as one
# find all file names ending in .csv 
files2 <- dir(pattern = "*.csv")
files2
# read in the data
data3 <- files2 %>%
  map(read_csv) %>%    # read in all the files individually, using
                       # the function read_csv() from the readr package
  reduce(rbind)        # reduce with rbind into one dataframe
data3

 

Please follow and like us:
error

About shibatau

I was born and grown up in Kyoto. I studied western philosophy at the University and specialized in analytic philosophy, especially Ludwig Wittgenstein at the postgraduate school. I'm interested in new technology, especially machine learning and have been learning R language for two years and began to learn Python last summer. Listening toParamore, Sia, Amazarashi and MIyuki Nakajima. Favorite movies I've recently seen: "FREEHELD". Favorite actors and actresses: Anthony Hopkins, Denzel Washington, Ellen Page, Meryl Streep, Mia Wasikowska and Robert DeNiro. Favorite books: Fyodor Mikhailovich Dostoyevsky, "The Karamazov Brothers", Shinran, "Lamentations of Divergences". Favorite phrase: Salvation by Faith. Twitter: @shibatau

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.