行列のデータとして、以下のようなものがあったとする。
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。
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=",")
とやれば同じことが実現できる。