I am using R to access some old FORTRAN input files and have some problems about sinking a data frame into a text file and keep its format.
My approach are:
- Use
read.tableto import data. - Adjust numbers in one column (multiply by a scalar).
- Save everything back using
write.tablefunction.
My code:
con <- file(paste(pth,'/Input/met/G_test.MET', sep=""))
aaa <- read.table(con)
aaa[,2]=aaa[,2]*0.1
write.table(aaa)
close(con)
My approach failed to work because it changed the format of the input file (It ignored spaces between columns). My question: is there a good way to conduct these three steps and maintain the same format? I can use readLines to keep the format, then I have to modify all the numbers in a big loop.
Here is how the data look (I knew the number of spaces between columns):
010192 0.00 0.04 8.3
010292 0.33 0.02 7.5
010392 0.61 0.23 11.7
010492 0.00 0.04 10.0
010592 0.00 0.07 10.6
010692 0.00 0.02 8.9
010792 0.00 0.19 9.4
010892 0.00 0.30 9.4
010992 0.00 0.08 11.4
Thanks for any suggestions.
UPDATE
Since I have to maintain the format and update numbers from one columns. I came up a 'hybrid' approach. This method worked but I appreciate suggestions on the standard approach.
- Use readLines to load data as characters in order to keep the format and maintain the staring zeros.
- Use read.table to load data as a data.frame and modify them
Replace numbers in a loop.
con_rain<- file(paste(pth,'/Out_Test/GA1LEVAP.MET', sep="")) a_rain=readLines(con_rain) b_rain=read.table(con_rain) for (i in 1:731){ a_rain[i]=paste(substr(a_rain[i],1,13),sprintf("%3.2f", b_rain[i,2]*p[19]),substr(a_rain[i],18,37),sep="") } writeLines(a_rain, paste(pth,'/Out_Test/GA1LEVAP.MET', sep=""))
write.tableto behave differently than it's documented defaults?