我有一个有20行51列的矩阵。我想将此数据打印到纯文本文件。我希望每行中的元素(浮点数)用空格分隔,并且每行的末尾都有一个换行符。
我尝试过使用MASS包(write.matrix),虽然肉眼看来正在做正确的事情,但当我尝试使用perl脚本解析文件时,在白色空间上进行简单的拆分不生成51个元素的数组(而是更小的元素),所以很明显元素不是空格分隔的。
我是R的新手,虽然我拥有不错的统计技能,但我似乎对数据展示方面感到厌烦。
感谢。
答案 0 :(得分:8)
write.table(mtcars, file = "mtcars.txt", sep = " ")
怎么样?
或类似的东西:
set.seed(0)
( m <- matrix(rnorm(100), ncol = 10) )
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1.262954285 0.7635935 -0.22426789 -0.2357066 1.7579031 0.26613736
[2,] -0.326233361 -0.7990092 0.37739565 -0.5428883 0.5607461 -0.37670272
[3,] 1.329799263 -1.1476570 0.13333636 -0.4333103 -0.4527840 2.44136463
[4,] 1.272429321 -0.2894616 0.80418951 -0.6494716 -0.8320433 -0.79533912
[5,] 0.414641434 -0.2992151 -0.05710677 0.7267507 -1.1665705 -0.05487747
[6,] -1.539950042 -0.4115108 0.50360797 1.1519118 -1.0655906 0.25014132
[7,] -0.928567035 0.2522234 1.08576936 0.9921604 -1.5637821 0.61824329
[8,] -0.294720447 -0.8919211 -0.69095384 -0.4295131 1.1565370 -0.17262350
[9,] -0.005767173 0.4356833 -1.28459935 1.2383041 0.8320471 -2.22390027
[10,] 2.404653389 -1.2375384 0.04672617 -0.2793463 -0.2273287 -1.26361438
[,7] [,8] [,9] [,10]
[1,] 0.35872890 0.01915639 -0.7970895 1.29931230
[2,] -0.01104548 0.25733838 1.2540831 -0.87326211
[3,] -0.94064916 -0.64901008 0.7721422 0.00837096
[4,] -0.11582532 -0.11916876 -0.2195156 -0.88087172
[5,] -0.81496871 0.66413570 -0.4248103 0.59625902
[6,] 0.24226348 1.10096910 -0.4189801 0.11971764
[7,] -1.42509839 0.14377148 0.9969869 -0.28217388
[8,] 0.36594112 -0.11775360 -0.2757780 1.45598840
[9,] 0.24841265 -0.91206837 1.2560188 0.22901959
[10,] 0.06528818 -1.43758624 0.6466744 0.99654393
然后:
write.table(m, file = "m.txt", sep = " ", row.names = FALSE, col.names = FALSE)
您可能希望将row.names
和col.names
保留为TRUE
(默认),以相应地保留行名和列名。