What's the best way to import data and fill a list in R with empty vectors whose names correspond to file content?

19 Views Asked by At

I've been trying to create a list based on a reference file but I can't make it work. I have a .txt file that has a format like this:

Vert 007, Horiz 002

Vert 007, Horiz 004

Vert 005, Horiz 006

Vert 012, Horiz 002

Next Power

Vert 003, Horiz 003

Vert 008, Horiz 005

Vert 012, Horiz 001

Vert 002, Horiz 001

Next Power

Vert 009, Horiz 001

Vert 005, Horiz 003

Vert 010, Horiz 005

Vert 001, Horiz 002

I'm trying to make a list where the first element of the list has empty vectors, named Vert 007, Horiz 002, Vert 007, Horiz 004, Vert 005, Horiz 006, Vert 012, Horiz 002. Then when it sees "Next power", creates a second element with empty vectors named whatever is after the "Next Power", and continues the same thing till there is no more Next Power and sublists.

file_list <- list()

file_list[[1]] <- list()

for (line in file_content) {
  if (grepl("Next Power", line)) {
    file_list <- append(file_list, list(list()))
  } else {
        subfolder_name <- gsub("Vert (\\d+), Horiz (\\d+)", "Vert \\1, Horiz \\2", line)
            if (!subfolder_name %in% names(file_list[[length(file_list)]])) {
      file_list[[length(file_list)]][[subfolder_name]] <- list()
    }
        file_list[[length(file_list)]][[subfolder_name]] <- append(file_list[[length(file_list)]][[subfolder_name]], line)
  }
}

But this makes the vectors to be a list too. I have actual data files with the same names of these vectors that I'd like to fill in with later, but first things first.

0

There are 0 best solutions below