Search code examples
rfile-ioexportcbind

How to export data in text file using R in the correct format?


I have 3 data variables created in R with the following information in each Variable 1: coordinate

x   y 
0.1 0.1 

Variable 2: mz

100.0 
100.1 
100.2 
100.3 
....
....
999.9

Variable 3: intensity

4.533154e-01  
2.997068e-01  
4.542300e-01  
2.905961e-01  
4.636095e-01
.....
.....

Now I want to export this information as a text file. Such that I have the following format

 x   y 
0.1 0.1 
100.0   2.905961e-01 
100.1   4.533154e-01  
100.2   2.997068e-01 
100.3   4.542300e-01 
....
....
999.9   2.905961e-01

I wrote the following code for this in R:

spectralData<-cbind(mz, intensity, deparse.level = 0)
foo<-c('%2.1f', '%2.8f')
cbar<-sapply(1:2,function(j) sprintf(foo[j],spectralData[,j]))
write(t(cbar),'/Desktop/cbar.txt',ncolumns=2)

data<-rbind(coordinate,spectralData,deparse.level = 0)
write.table(data, "/Desktop/test.txt", row.names = FALSE)

I receive the text file but with it has two issues. First, I get row numbers as an additional column. How should I avoid this? Second, the precision of the numbers changes for both mz and intensity columns. How can I get the same precision after decimal? Here is what the exported data looks like

"x" "y"
"1" 0.100000001490116 0.100000001490116
"2" 100 -1.77635683940025e-15
"3" 100.099998474121 0.0266907754084524
"4" 100.199996948242 0.0533815508169102
"5" 100.300003051758 3.5527136788005e-15
"6" 100.400001525879 0.135286505970676
"7" 100.5 0.0286329399926419

Solution

  • If you want specific precisions for each column (part of your question, I believe), one way is to start by running your data frame through a sprintf statement to create an array of character strings. Then use write to write the data to a file -- the quote marks will not be carried thru. Here's an example.

    fbar<-sin((1:10)/10)
    fbar<-matrix(fbar,5)
    #fbar
    #           [,1]      [,2]
    #[1,] 0.09983342 0.5646425
    #[2,] 0.19866933 0.6442177
    #[3,] 0.29552021 0.7173561
    #[4,] 0.38941834 0.7833269
    #[5,] 0.47942554 0.8414710
    foo<-c('%2.8f', '%2.3f')
    cbar<-sapply(1:2,function(j) sprintf(foo[j],fbar[,j]) )
    write(t(cbar),'cbar.txt',ncolumns=2)
    #cbar
    #0.09983342 0.565
    #0.19866933 0.644
    #0.29552021 0.717
    #0.38941834 0.783
    #0.47942554 0.841