簡體   English   中英

將帶有多個定界符的長字符串分成多列

[英]Separating a long string with multiple delimiters into multiple columns

我有這樣格式化的數據:

X    Raw data
1     %100,02231,      ,001,013, -00007,000,999 &IC  ,001,013 >vs     ,0652 ?2    ,2    ,00007 .vss    ,0655 ?2    ,2    ,00007 .mdb    ,0700 ?2    ,2    ,00007 .arn    ,0704 ?1    ,1
2     %100,02231,      ,001,023, -00008,000,999 &IC  ,001,023 >vs     ,0652 ?3    ,3    ,00008 .vss    ,0655 ?2    ,2    ,00008 .mdb    ,0700 ?2    ,2    ,00008 .arn    ,0704 ?1    ,1    ,00008 +gs     ,0713,0714 ?2    ,2    ,00008 .bzl    ,0719 ?2    ,2    ,00008 .krg    ,0724 ?1    ,1

等等。

我想將這些原始數據轉換成漂亮的表格形狀。 我知道如何使用tidyr的單獨功能將某些東西分開, tidyr所示:

DFx <- separate(DF, Raw.data, into="Starting station", sep=">", extra="warn", fill = "right")

>例如表示起始站。 &將指示火車類型。 在上面的示例中,它將起始站點與其余站點分開。 我正在尋找將這個大數據集(僅對部分行進行采樣)放入漂亮表的最佳方法。 我不怕一點體力勞動,只是在尋找可以使我朝正確方向前進的任何指針。 謝謝。

我用的timetbls.dat文件可以從以下網址下載: 點擊這里

有關數據格式的文檔(不幸的是,使用荷蘭語,但可能會有所幫助,因為您仍然可以看到數據的輪廓),請參閱第9 / 28-11 / 28頁: 此處

記錄文件!

讓我們先將大量代碼移開(滾動過去以獲取列表格式的一些注釋和注釋):

# Reference: Section 5 of IFF Standaard
parse_iff_timetable <- function(path) {

  suppressPackageStartupMessages({
    require("stringi", quietly = TRUE, warn.conflicts = FALSE)
    require("tidyverse", quietly = TRUE, warn.conflicts = FALSE)
  })

  lines <- stri_read_lines(path.expand(path)) # read in all the lines

  starts <- which(grepl("^#", lines)) # find all the records
  ends <- c(starts[-1], length(lines))

  pb <- progress_estimated(length(starts)) # this took 3m on my system so progress bars might be handy

  map2(starts, ends, ~{

    pb$tick()$print()

    rec_num <- ""
    rec <- list(service = list(), stop = list())
    index <- 0

    for (l in lines[.x:.y]) { # iterate over the record

      if (stri_sub(l, 1, 1) == "#") { # (ritnummer)

        stri_sub(l, 1, 1) <- ""
        rec_num <-  l

      } else if (stri_sub(l, 1, 1) == "%") { # (vervoerder)

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        set_names(
          tmp, c("company_number", "service_number", "variant", "first_stop",
                 "last_stop", "service_name")
        ) -> tmp

        rec$service <- append(rec$service, list(as.list(tmp)))

      } else if (stri_sub(l, 1, 1) == "-") { # (voetnoot)

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("footnote", "first_stop", "last_stop"))
        tmp <- as.list(tmp)

        rec$validity <- tmp

      } else if (stri_sub(l, 1, 1) == "&") { # (vervoerssort)

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("mode", "first_stop", "last_stop"))
        tmp <- as.list(tmp)

        rec$transport <- tmp

      } else if (stri_sub(l, 1, 1) == "*") { # (attribuut)

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("code", "first_stop", "last_stop", "unknown"))
        tmp <- as.list(tmp)

        rec$attribute <- tmp

      } else if (stri_sub(l, 1, 1) == ">") { # (begin van de rit)

        index <- index + 1

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("station_short", "departure_time"))
        tmp <- as.list(tmp)
        tmp$index <- index
        tmp$arrival_time <- NA_character_

        rec$stop <- list(tmp)

      } else if (stri_sub(l, 1, 1) == ".") { # (korte stop)

        index <- index + 1

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("station_short", "departure_time"))
        tmp <- as.list(tmp)
        tmp$index <- index
        tmp$arrival_time <- tmp$departure_time

        rec$stop <- append(rec$stop, list(tmp))

      } else if (stri_sub(l, 1, 1) == ";") { # (passeer station)

        index <- index + 1

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("station_short"))
        tmp <- as.list(tmp)
        tmp$index <- index
        tmp$arrival_time <- NA_character_
        tmp$departure_time <- NA_character_

        rec$stop <- append(rec$stop, list(tmp))

      } else if (stri_sub(l, 1, 1) == "+") { # (a/v stop)

        index <- index + 1

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("station_short", "arrival_time", "departure_time"))
        tmp <- as.list(tmp)
        tmp$index <- index

        rec$stop <- append(rec$stop, list(tmp))

      } else if (stri_sub(l, 1, 1) == "?") { # (spoor)

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("arrival_platform", "departure_platform", "footnote"))
        tmp <- as.list(tmp)
        tmp$index <- index

        if (stri_sub(tmp$arrival_platform, 1,1) != stri_sub(tmp$departure_platform, 1,1)) {
          message(
            sprintf(
              "\nNOTE: Difference in arrival/departure platforms: %s/%s (Record: #%s)",
              tmp$arrival_platform, tmp$departure_platform, rec_num
            )
          )
        }

        rec$platform <- tmp

      } else if (stri_sub(l, 1, 1) == "<") { # (eind van de rit)

        index <- index + 1

        stri_sub(l, 1, 1) <- ""
        tmp <- stri_trim_both(stri_split_fixed(l, ",")[[1]])
        tmp <- set_names(tmp, c("station_short", "arrival_time"))
        tmp <- as.list(tmp)
        tmp$index <- index
        tmp$departure_time <- NA_character_

        rec$stop <- append(rec$stop, list(tmp))

      }

    }

    rec

  })

}

我在^^中使用stringi ,因為該標准很可能在許多語言環境中使用,並且stringi應該為我們注意編碼規范化。

如果我在13MB dat文件上運行該文件:

ns_tbl <- parse_iff_timetable("~/data/ns-latest/timetbls.dat")

它需要大約300萬英鎊(快速的逐個字符操作不是R的強項之一),並且在其中有一條警告提示,其中大約有一條記錄具有不同的到達/離開平台。 Rcpp版本的速度可能會快得多。 由於順序實際上並不重要,因此只要對代碼進行較小的更改, furrrpbapply包也可以將時間減少到<1m。

基本習慣是對每條“記錄”逐行進行處理,並建立一個大型的嵌套列表結構(無論如何,這都不是“固定的”數據)。

讓我們瀏覽一個記錄(第一個):

str(ns_tbl[1], 2)
## List of 1
##  $ :List of 5
##   ..$ service  :List of 2
##   ..$ stop     :List of 34
##   ..$ validity :List of 3
##   ..$ transport:List of 3
##   ..$ platform :List of 4

stop元素很大,所以讓我們先看看其他元素:

str(ns_tbl[[1]][-2], 3)
## List of 4
##  $ service  :List of 2
##   ..$ :List of 6
##   .. ..$ company_number: chr "100"
##   .. ..$ service_number: chr "11410"
##   .. ..$ variant       : chr ""
##   .. ..$ first_stop    : chr "001"
##   .. ..$ last_stop     : chr "002"
##   .. ..$ service_name  : chr "Nachtnettrein"
##   ..$ :List of 6
##   .. ..$ company_number: chr "100"
##   .. ..$ service_number: chr "01412"
##   .. ..$ variant       : chr ""
##   .. ..$ first_stop    : chr "002"
##   .. ..$ last_stop     : chr "008"
##   .. ..$ service_name  : chr "Nachtnettrein"
##  $ validity :List of 3
##   ..$ footnote  : chr "00002"
##   ..$ first_stop: chr "000"
##   ..$ last_stop : chr "999"
##  $ transport:List of 3
##   ..$ mode      : chr "IC"
##   ..$ first_stop: chr "001"
##   ..$ last_stop : chr "008"
##  $ platform :List of 4
##   ..$ arrival_platform  : chr "5"
##   ..$ departure_platform: chr "5"
##   ..$ footnote          : chr "00002"
##   ..$ index             : num 34

而且,我們可以看一下第一站,第二站(沒有到達/到達的目的地,所以我想那不是到達的目的地),到達/離開的一個到達和最后一個到達:

str(ns_tbl[[1]]$stop[c(1, 2, 6, 34)], 2)
## List of 4
##  $ :List of 4
##   ..$ station_short : chr "rtd"
##   ..$ departure_time: chr "2532"
##   ..$ index         : num 1
##   ..$ arrival_time  : chr NA
##  $ :List of 4
##   ..$ station_short : chr "rtn"
##   ..$ index         : num 2
##   ..$ arrival_time  : chr NA
##   ..$ departure_time: chr NA
##  $ :List of 4
##   ..$ station_short : chr "gd"
##   ..$ arrival_time  : chr "2550"
##   ..$ departure_time: chr "2557"
##   ..$ index         : num 6
##  $ :List of 4
##   ..$ station_short : chr "ut"
##   ..$ arrival_time  : chr "2751"
##   ..$ index         : num 34
##   ..$ departure_time: chr NA

我將根據評論通過更多信息來對此進行修改。

您可以使用標准的R慣用法將部分或全部這些變成數據框:

map_df(ns_tbl, ~{
  as.list(c(
    unlist(.x$validity),
    unlist(.x$transport),
    unlist(.x$platform)
  )) -> out
  out$service <- list(.x$service)
  out$stop <- list(.x$stop)
  out
}) %>% 
  glimpse()
## Observations: 40,901
## Variables: 9
## $ footnote           <chr> "00002", "00003", "00004", "00005", ...
## $ first_stop         <chr> "001", "001", "001", "001", "001", "...
## $ last_stop          <chr> "008", "008", "007", "007", "007", "...
## $ mode               <chr> "IC", "IC", "IC", "IC", "IC", "IC", ...
## $ arrival_platform   <chr> "5", "5", "5", "5", "5", "5", "5", "...
## $ departure_platform <chr> "5", "5", "5", "5", "5", "5", "5", "...
## $ index              <chr> "34", "34", "34", "34", "34", "34", ...
## $ service            <list> [[["100", "11410", "", "001", "002"...
## $ stop               <list> [[["rtd", "2532", 1, NA], ["rtn", 2...

您仍然需要處理將多個記錄取消嵌套的位。

另外,頂層index實際上只是停止次數的元數據,但我會更好地為您命名。

理想情況下,可以解析較小的元數據文件,並使用各種縮寫名稱的擴展版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM