|
| 1 | +#' Read Obs_Node.out |
| 2 | +#' |
| 3 | +#' @param path path to Obs_Node.out |
| 4 | +#' @param to_longer convert table to longer format (default: TRUE) |
| 5 | +#' @importFrom stringr str_trim str_split str_replace_all str_remove |
| 6 | +#' @importFrom readr read_csv |
| 7 | +#' @export |
| 8 | +read_obsnode <- function(path, to_longer = TRUE) { |
| 9 | + # Lese die Datei ein |
| 10 | + lines <- readLines(path) |
| 11 | + |
| 12 | + lines <- lines[seq_len(grep("end", lines)-1)] |
| 13 | + |
| 14 | + # Lese die Node-Namen aus Zeile 9 ein |
| 15 | + nodes_idx <- grep("Node", lines) |
| 16 | + nodes_line <- lines[nodes_idx] |
| 17 | + |
| 18 | + node_names <- nodes_line %>% |
| 19 | + stringr::str_trim() %>% |
| 20 | + stringr::str_split("\\s{2,}", simplify = TRUE) %>% |
| 21 | + as.vector() %>% |
| 22 | + stringr::str_replace_all(pattern = "\\(\\s?", replacement = "") %>% |
| 23 | + stringr::str_remove("\\)") %>% |
| 24 | + tolower |
| 25 | + |
| 26 | + timeseries_idx <- grep("time", lines) |
| 27 | + |
| 28 | + headers <- lines[timeseries_idx] %>% |
| 29 | + stringr::str_trim() %>% |
| 30 | + stringr::str_replace_all("\\s+", ",") %>% |
| 31 | + stringr::str_split(pattern = ",", simplify = TRUE) %>% |
| 32 | + as.vector() %>% |
| 33 | + tolower() |
| 34 | + |
| 35 | + block_start <- grep(pattern = "^h$", headers) |
| 36 | + block_end <- c(block_start[2:length(block_start)] - 1, length(headers)) |
| 37 | + |
| 38 | + n_blocks <- length(block_start) |
| 39 | + |
| 40 | + headers_clean <- c("time", lapply(seq_len(n_blocks), function(i) { |
| 41 | + |
| 42 | + headers_sel <- headers[block_start[i]:block_end[i]] |
| 43 | + is_conc <- grepl("conc", headers_sel) |
| 44 | + |
| 45 | + if(sum(is_conc) > 0) { |
| 46 | + headers_sel[is_conc] <- sprintf("%s%d", |
| 47 | + headers_sel[is_conc], |
| 48 | + seq_len(sum(is_conc))) |
| 49 | + } |
| 50 | + |
| 51 | + sprintf("%s_%s", node_names[i], headers_sel) |
| 52 | + }) %>% unlist()) |
| 53 | + |
| 54 | + |
| 55 | + dat_csv <- c(paste0(headers_clean, collapse = " "), |
| 56 | + lines[(timeseries_idx+1):length(lines)]) %>% |
| 57 | + stringr::str_trim() %>% |
| 58 | + stringr::str_replace_all("\\s+", ",") |
| 59 | + |
| 60 | + path_csv <- file.path(tempdir(), "obs_node.csv") |
| 61 | + |
| 62 | + writeLines(dat_csv, path_csv) |
| 63 | + |
| 64 | + dat <- readr::read_csv(path_csv) |
| 65 | + |
| 66 | + if(to_longer) { |
| 67 | + dat %>% |
| 68 | + tidyr::pivot_longer( - time) %>% |
| 69 | + tidyr::separate(col = "name", into = c("node", "variable"), sep = "_") |
| 70 | + } else { |
| 71 | + dat |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments