readrパッケージを使ったファイル入出力方法。 読み込んだデータの型はtibble(データフレームの一種)になる。
library(tidyverse)
read_csv(): “,“区切りのファイルからread_csv2(): “;“区切りのファイルからread_tsv(): タブ区切りのファイルからread_delim(): 任意の区切り文字のファイルからread_fwf(): 固定幅(fixed width)のファイルから
fwf_widths(), fwf_positions(): フィールド幅や位置の取得read_table(): 空白区切りの固定長幅ファイルからread_log(): apacheのlogファイルから例
heights <- read_csv("diet.csv")
read_csv("a,b
1,2")
Rの基本関数read.csv()に比べて10倍くらい速いらしい。
read_csv("diet.csv", skip=2) # 2行読み飛ばす
read_csv("diet.csv", comment="#") # "#"で始まる行を読み飛ばす
末尾を読み飛ばしたいときには,他のコマンドと組み合わせてなんとかする。 以下は,初めの10行と,終わりの3行をスキップする例。
read_lines("diet.csv",skip=10) %>%
head(-3) %>%
read_csv()
read_csv("diet.csv",col_names = FALSE)
read_csv("diet.csv", col_names = c("x", "y", "z"))
read_csv("diet.csv", na = ".")
write_csv(), write_tsv()
データの保存形式は以下になる
注意: write_csv()では,各列のデータ型の情報がなくなる
write_rds(), read_rds()を入出力に使う。(RDS は R’s custom binary format)write_feather(),read_featherを使う。RDSよりも速くて,R以外でも使える。ただし,featherでは使えない形式がある。以下は,ページャ機能utils::page()を使ってrdsファイル読み込んで表示するRスクリプト例。
height = 30L # for example
width = 160L
options(
tibble.width = Inf,
tibble.print_max = Inf,
width=10000L # folding width on terminal
)
fname <- commandArgs(trailingOnly=TRUE)[1]
dat <- read_rds(fname) %T>% page('print')
上記スクリプト名をless.rとした場合,以下のように実行すれば,rdsファイルの表示をできる。
$ Rscript less.r <filename>.rds
csvファイルを見るなら,スクリプト中のread_rdsをread_csvに変えたらいいが,それよりはlessを使って直接見たほうが早い。
library('tidyverse')
source_dir="/home/someone/data/"
files <- list.files(path=source_dir, pattern=".csv$", full.names=T) %>%
map(read_csv, skip = 1) %>%
reduce(bind_rows)
purrr::reduceは,リスト要素を順に関数に引き渡す命令。 この例では,ファイルから読み込んだデータフレームが順にrbindで結合される。
nested dataframeにする方法もある。
data <- list.files(path=source_dir, pattern=".csv$", full.names=T) %>%
data_frame(filename=.) %>%
mutate(contents=map(filename, ~ read_csv(file.path(source_dir, .)))
)
2行目でファイル名一覧を要素とするdataframeを作り,3行目で各ファイルの中身を格納したデータフレーム(nested dataframe)を要素とする列(contents)を追加している。 これを一つのデータフレームに変換したければ
unnest(data)