←戻る

データの入出力

行列のデータとして、以下のようなものがあったとする。

hoge <- matrix(
  c(15, 20, 25, 10, 30,
    10, 25, 20, 25, 20),
  byrow=TRUE, ncol=5)
rownames(hoge) <- c("A", "B")
colnames(hoge) <- c("Cherry", "Apple", "Grape", "Banana", "Other")
print(hoge)
##   Cherry Apple Grape Banana Other
## A     15    20    25     10    30
## B     10    25    20     25    20

テキストファイルへの保存・読み込み

ファイルへの行列変数の出力は

write.table(hoge, file="hoge.txt")

で行う。出力されたファイルhoge.txtの中身は

"Cherry" "Apple" "Grape" "Banana" "Other"
"A" 15 20 25 10 30
"B" 10 25 20 25 20

となる。このファイルを読み込むには

hoge <- read.table("hoge.txt")

でOK。

CSVファイルへの保存・読み込み

ExcelとのデータのやりとりはCSVファイルのほうが便利なこともある。

write.csv(hoge, file="hoge.csv")

で行う。hoge.csvの内容は

"X","Cherry","Apple","Grape","Banana","Other"
"1","A",15,20,25,10,30
"2","B",10,25,20,25,20

となる。読み込むには

hoge <- read.csv("hoge.csv", header=TRUE)
print(hoge)
##   X Cherry Apple Grape Banana Other
## 1 A     15    20    25     10    30
## 2 B     10    25    20     25    20

write.csv()read.csv()も、write.table()read.table()のラッパーなので、

write.table(hoge, file="hoge.csv", sep=",")

とやれば同じことが実現できる。



[←戻る](index.html)