如何在没有列名的情况下从文件中写入和读取矩阵?

时间:2014-11-28 03:00:41

标签: r

矩阵Aexample是:

Aexample
[,1] [,2] [,3] [,4]
[1,]  0.6  0.4 0.00  0.0
[2,]  0.4  0.4 0.00  0.0
[3,]  0.4  0.4 0.00  0.0
[4,]  0.0  0.0 0.40  0.4
[5,]  0.0  0.0 0.34  0.4
[6,]  0.0  0.0 0.40  0.4

通过

保存到文件中
  

write.table(例如,file ="〜/ R / Aexample",row.names = FALSE,col.names = FALSE);

然后我读了

  

Aexample = as.matrix(read.table(file ="〜/ R / Aexample"));

但结果总是有 V1 V2 V3 V4 列名称,我不想要:

    V1  V2   V3  V4
[1,]  0.6  0.4 0.00  0.0
[2,]  0.4  0.4 0.00  0.0
[3,]  0.4  0.4 0.00  0.0
[4,]  0.0  0.0 0.40  0.4
[5,]  0.0  0.0 0.34  0.4
[6,]  0.0  0.0 0.40  0.4

保存Aexample矩阵然后从文件中读取并获取原始Aexample矩阵的最简单方法是什么? (不要读取aa = as.matrix(read.table(file ="〜/ R / Aexample"))然后从包含多行代码的aa创建Aexample)

1 个答案:

答案 0 :(得分:1)

您可以分两步完成:

1

Aexample = as.matrix(read.table(file="~/R/Aexample"))

2

colnames(Aexample) <- NULL

示例

aaa<-matrix(1:24,nrow=6)

> aaa
     [,1] [,2] [,3] [,4]
[1,]    1    7   13   19
[2,]    2    8   14   20
[3,]    3    9   15   21
[4,]    4   10   16   22
[5,]    5   11   17   23
[6,]    6   12   18   24

write.table(aaa,"aaa.txt",col.names=F,row.names=F)

bbb<-as.matrix(read.table(file="aaa.txt",header=T))
colnames(bbb)<-NULL

> bbb
     [,1] [,2] [,3] [,4]
[1,]    1    7   13   19
[2,]    2    8   14   20
[3,]    3    9   15   21
[4,]    4   10   16   22
[5,]    5   11   17   23
[6,]    6   12   18   24