1

I have the following text file, it contains several chunk of table. Each chunk is separated by white space.

GENERALIZED BORN:
Complex Energy Terms
Frame #,BOND,ANGLE
0,6603.0521,7264
1,7434.9885,7602

Receptor Energy Terms
Frame #,BOND,ANGLE
0,6140.6338,5383.1241
1,6885.2965,5653.6637

Ligand Energy Terms
Frame #,BOND,ANGLE
0,462.4183,1881.428
1,549.692,1949.0482

How can I use R to parse this single text file into list of three data frames, or tibbles?

I tried this but failed:

library(readr)
readr::read_lines_chunked("myfile.txt", skip =1, chunk_size = 4)

Because readr::read_lines_chunked can't recognized the white space separator between chunks.

1 Answer 1

2

It's not clear to me if that function was suppose to be used like that. My guess is not. But you can parse the data manually. Create a list, parse out chunks and save it into a list.

xy <- readLines(con = "test.txt")
xy <- xy[-1]  # remove GENERALIZED BORN

xy <- xy[which(xy != "")]
# Start of a break is needed for names and subsetting in a loop.
breaks <- which(grepl("^.*Energy Terms", x = xy))

dfs <- vector(mode = "list", length = length(breaks))
names(dfs) <- xy[breaks]

# Adding one accounts for the Energy Terms line. It's either here
# or in the loop.
chunks <- breaks + 1

for (chunk in seq_along(chunks)) {
  # If we extract the name and use it to subset, the order of the
  # dfs doesn't really matter.
  chk.name <- xy[chunks[chunk] - 1]
  
  from <- chunks[chunk]
  to <- chunks[chunk + 1] - 2
  
  # When working with the last chunk, this sets the end of the text.
  if (is.na(to)) {
    to <- length(xy)
  }
  
  chk <- xy[from:to]

  tmp <- read.table(
    text =  paste(chk, collapse = "\n"), 
    header = TRUE, 
    comment.char = "", 
    sep = ","
    )
  
  dfs[[chk.name]] <- tmp
}

And the result

$`Complex Energy Terms`
  Frame..     BOND ANGLE
1       0 6603.052  7264
2       1 7434.989  7602

$`Receptor Energy Terms`
  Frame..     BOND    ANGLE
1       0 6140.634 5383.124
2       1 6885.297 5653.664

$`Ligand Energy Terms`
  Frame..     BOND    ANGLE
1       0 462.4183 1881.428
2       1 549.6920 1949.048
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.