[R] reading a matrix from a file

Francisco J. Zagmutt gerifalte28 at hotmail.com
Tue Jun 27 18:32:36 CEST 2006


Dear Cuau

More details on your posting would have helped. From your example it seems 
that the matrix you are trying to import is just a comma Separated text 
file. If that's the case, you can use read.csv and matrix to import those 
numbers and then make a matrix in R.  Assuming the matrix has 3 rows and 4 
columns you can do the following:

x=read.csv("mymatrix.txt", header=FALSE) #Reads your file
dim(x)  #Tells you the dimensions of object x in rows and columns
[1] 3 4

newMat= as.matrix(x) #Creates matrix from imported data
is.matrix(newMat) #Tests whether the object newMat is of class matrix
[1] TRUE


I hope this helps

Francisco

Dr. Francisco J. Zagmutt
College of Veterinary Medicine and Biomedical Sciences
Colorado State University




>From: Cuau <cuauv at yahoo.com>
>To: r-help at stat.math.ethz.ch
>Subject: [R] reading a matrix from a file
>Date: Tue, 27 Jun 2006 08:06:36 -0700 (PDT)
>
>
>    Hello everyone,
>
>    I'm writting a little script that will read a matrix from a file
>
>   i.e.
>
>   0,.11,.22,.4
>   .11,0,.5,.3
>   .22,.5,0,.7
>   anb so on
>
>   and will then calculate some standard stats for nets (i.e. 
>centralization, degree, etc).
>
>     So far I have opened the file and read the contents, however I' m 
>using readLines(filename)
>    to read the file and it returns it as one big String with no divitions. 
>I tried using
>   strsplit(String)
>   to split it but eventhough is working I'm not able to put the output of 
>the above into a matrix.
>
>    Below is an example of what I have done
>
>
>   > INfile<-file("mTest.txt", "r")
>   > readLines(INfile)->matrix
>   > matrix
>   [1] "1, 2, 3"
>   > strsplit(matrix, ",")->splitLine
>   > splitLine
>   [[1]]
>   [1] "1"  " 2" " 3"
>
>   > netMatrix <-matrix(c(splitLine), nrow=1,ncol=3)
>   > netMatrix
>        [,1]         [,2]         [,3]
>   [1,] Character,3 Character,3 Character,3
>
>
>    Does anyone have an idea how can I read a matrix and store it in the 
>form of a matrix.
>
>   thks
>
>   -Cuau Vital
>
>
>
>---------------------------------
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! 
>http://www.R-project.org/posting-guide.html



More information about the R-help mailing list