[R] Write text file in Fortran format

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Wed Sep 21 18:12:42 CEST 2022


You forgot to cc the list.

Here is a solution, I believe the comments explain the several steps.
It's a matter to read in the file, separate the table from the rest, 
update the 3rd column, assemble the pieces back together and write to file.

# this path depends on the OP's system
path <- "~/Temp"
fl <- list.files(path, pattern = "Air.txt", full.names = TRUE)
# read the file as text
txt <- readLines(fl)

# find lines starting with an asterisk
i <- grep("^\\*", txt)
# keep the other lines
txt_table <- txt[-i]
# find the lines starting or after the first blank line
j <- which(seq_along(txt_table) >= which(txt_table == ""))
# keep the other lines
txt_table <- txt_table[-j]
txt_table <- trimws(txt_table)

df1 <- read.table(text = txt_table)
# multiply 3rd column by 2
df1[[3]] <- 2*df1[[3]]

# format the table's lines to write them back to file
fmt <- "%14.5f %13.5f %13.5f %8.2f %8.2f %8.2f %7s %8s %10s %9s %9d"
new_data <- sprintf(fmt,
                     df1[[1]], df1[[2]], df1[[3]], df1[[4]],
                     df1[[5]], df1[[6]], df1[[7]], df1[[8]],
                     df1[[9]], df1[[10]], df1[[11]])

j <- which(seq_along(txt) >= which(txt == ""))
# assemble the header, the table and the footer
txt_new <- c(txt[i], new_data, txt[j])

# this is not in the question,
# I'm not rewriting the original
fl2 <- file.path(dirname(fl), "Air2.txt")
writeLines(txt_new, fl2)

Hope this helps,

rui Barradas

Às 15:55 de 21/09/2022, javad bayat escreveu:
> Dear Rui;
> I have no knowledge of the FORTRAN language. The text file that has been
> attached is a model's output file and I know that the format is in FORTRAN.
> I want to write a text file exactly similar to the attached text file using
> R programming.
> The steps below explain my goal:
> 1- Read the text file without the first 8 and last 2 rows as a dataframe.
> 2- Double the 3rd column values (or multiply by specific number).
> 3- Insert the removed first 8 rows of the original text file as header in
> the dataframe.
> 4- Insert the removed last 2 rows of the original text file at the end of
> dataframe.
> 5- Write the dataframe as a new text file exactly similar to the original
> text file.
> I have used excel but when I save it as text file, the format changes and
> is not similar to the attached text file.
> Sincerely
> On Wed, 21 Sep 2022, 16:46 Rui Barradas, <ruipbarradas using sapo.pt> wrote:
>> Hello,
>> The attached file ends with R-Help's end message. This is unrelated to
>> computer languages, Fortran, R or other.
>> And there is no such thing as a Fortran format.
>> Can you please describe the problem you have?
>> Rui Barradas
>> Às 07:09 de 21/09/2022, javad bayat escreveu:

More information about the R-help mailing list