[R] Reading data from file made by C fwrite

Thomas Lumley thomas at biostat.washington.edu
Tue Feb 29 20:46:21 CET 2000


On Tue, 29 Feb 2000, Kjetil Kjernsmo wrote:

> 
> I'm currently working on importing data from files created by a C program
> (that I have not written myself, I have the source code, but I don't know
> if the author wants to publish it yet). 
> 
> I really don't know much about C, but I can understand that the program
> writes to a file using 
> fwrite(MAP,sizeof(float),MAP_i*MAP_j,f)
> where MAP most probably is a pointer to a two-dimensional array of single
> precision floats. This is what I want to read into a matrix in R.
> 

We don't currently have any support for this in R. It's not that hard to
do, but it doesn't generalise that well to eg multiple variables.

What you want to do is to write a C function that accepts a filename and
a pointer to a vector of doubles. It should open the file, read each
float, cast it to double, and put it in the vector of doubles, then close
the file.
	
	void readTheFile(char **filename, double *workspace)

Calling this function from R would read the numbers into the supplied
vector, and you could then fix up the dimensions in R (I'm assuming you
know the size of the file here)

	a<-.C("readTheFile",filename,numeric(size.of.file))
	m<-a[[2]]
	dim(m)<-c(100,200) #for example


The manual on writing R Extensions should help.


	-thomas

Thomas Lumley
Assistant Professor, Biostatistics
University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list