Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print a matrix in R

I have a matrix that has 20 rows and 51 columns. I would like to print this data to a plain text file. I would like the elements (which are floating point numbers) in each row to be separated by spaces, and for there to be a newline at the end of every row.

I have tried using the MASS package (write.matrix), and while it appears to the naked eye to be doing the correct thing, when I try to parse the file with a perl script, doing a simple split on white space does not generate an array of 51 elements (but rather smaller ones), so clearly the elements are not space separated.

I am super new to R, and while I have decent stats skills, I seem to suck at the data presentation side.

Thanks.

like image 333
PNMNS Avatar asked Jan 19 '23 01:01

PNMNS


1 Answers

How about write.table(mtcars, file = "mtcars.txt", sep = " ")?

Or something like this:

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

and then:

write.table(m, file = "m.txt", sep = " ", row.names = FALSE, col.names = FALSE)

and you may want to leave row.names and col.names as TRUE (default), to keep row and column names, accordingly.

like image 155
aL3xa Avatar answered Jan 24 '23 15:01

aL3xa