當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R readr read_fwf 將固定寬度文件讀入 tibble

固定寬度文件可以是數字數據的非常緊湊的表示。解析速度也非常快,因為每行中的每個字段都位於相同的位置。不幸的是,解析起來很痛苦,因為您需要說明每個字段的長度。 Readr 旨在通過提供多種不同的方式來說明字段結構,使其盡可能簡單。

  • fwf_empty() - 根據空列的位置進行猜測。

  • fwf_widths() - 提供列的寬度。

  • fwf_positions() - 提供起始位置和結束位置的成對向量。

  • fwf_cols() - 提供成對的開始和結束位置或列寬的命名參數。

用法

read_fwf(
  file,
  col_positions = fwf_empty(file, skip, n = guess_max),
  col_types = NULL,
  col_select = NULL,
  id = NULL,
  locale = default_locale(),
  na = c("", "NA"),
  comment = "",
  trim_ws = TRUE,
  skip = 0,
  n_max = Inf,
  guess_max = min(n_max, 1000),
  progress = show_progress(),
  name_repair = "unique",
  num_threads = readr_threads(),
  show_col_types = should_show_types(),
  lazy = should_read_lazy(),
  skip_empty_rows = TRUE
)

fwf_empty(
  file,
  skip = 0,
  skip_empty_rows = FALSE,
  col_names = NULL,
  comment = "",
  n = 100L
)

fwf_widths(widths, col_names = NULL)

fwf_positions(start, end = NULL, col_names = NULL)

fwf_cols(...)

參數

file

文件路徑、連接或文字數據(單個字符串或原始向量)。

.gz.bz2.xz.zip 結尾的文件將自動解壓縮。將自動下載以 http://https://ftp://ftps:// 開頭的文件。遠程gz文件也可以自動下載並解壓。

文字數據對於示例和測試最有用。要被識別為文字數據,輸入必須用 I() 包裝,是包含至少一個換行符的字符串,或者是至少包含一個帶有換行符的字符串的向量。

使用值 clipboard() 將從係統剪貼板讀取。

col_positions

列位置,由 fwf_empty()fwf_widths()fwf_positions() 創建。要僅讀入選定的字段,請使用 fwf_positions() 。如果最後一列的寬度是可變的(參差不齊的 fwf 文件),則將最後一個結束位置提供為 NA。

col_types

NULLcols() 規範或字符串之一。有關更多詳細信息,請參閱vignette("readr")

如果是 NULL ,則所有列類型都將從輸入的 guess_max 行推斷出來,散布在整個文件中。這很方便(而且快速),但不夠穩健。如果猜測的類型錯誤,您需要增加 guess_max 或自己提供正確的類型。

list()cols() 創建的列規範必須為每一列包含一個列規範。如果您隻想讀取列的子集,請使用 cols_only()

或者,您可以使用緊湊的字符串表示形式,其中每個字符代表一列:

  • c = 字符

  • 我 = 整數

  • n = 數字

  • d = 雙

  • l = 邏輯

  • f = 因子

  • D = 日期

  • T = 日期時間

  • t = 時間

  • ? = 猜猜

  • _ 或 - = 跳過

默認情況下,讀取沒有列規範的文件將打印一條消息,顯示 readr 猜測的內容。要刪除此消息,請設置 show_col_types = FALSE 或設置 `options(readr.show_col_types = FALSE)。

col_select

要包含在結果中的列。您可以使用與dplyr::select() 相同的mini-language 來按名稱引用列。使用c() 可以使用多個選擇表達式。盡管這種用法不太常見,col_select 也接受數字列索引。有關選擇語言的完整詳細信息,請參閱?tidyselect::language

id

用於存儲文件路徑的列的名稱。當讀取多個輸入文件並且文件路徑中有數據(例如數據收集日期)時,這非常有用。如果NULL(默認值)則不會創建額外的列。

locale

區域設置控製默認值因地而異。默認區域設置為 US-centric(如 R),但您可以使用 locale() 創建自己的區域設置來控製默認時區、編碼、小數標記、大標記和日/月名稱等內容。

na

要解釋為缺失值的字符串的字符向量。將此選項設置為 character() 以指示沒有缺失值。

comment

用於標識評論的字符串。注釋字符之後的任何文本都將被默默忽略。

trim_ws

在解析每個字段之前是否應該刪除前導和尾隨空格(ASCII 空格和製表符)?

skip

讀取數據之前要跳過的行數。

n_max

讀取的最大行數。

guess_max

用於猜測列類型的最大行數。永遠不會使用超過讀取的行數。有關更多詳細信息,請參閱vignette("column-types", package = "readr")

progress

顯示進度條?默認情況下,它隻會在交互式會話中顯示,而不會在編織文檔時顯示。可以通過將選項 readr.show_progress 設置為 FALSE 來禁用自動進度條。

name_repair

列名的處理。默認行為是確保列名稱為 "unique" 。支持多種修複策略:

  • "minimal":除了名稱的基本存在之外,沒有名稱修複或檢查。

  • "unique"(默認值):確保名稱唯一且不為空。

  • "check_unique" :沒有名稱修複,但檢查它們是 unique

  • "universal" :將名稱命名為 unique 並進行語法設置。

  • 函數:應用自定義名稱修複(例如,name_repair = make.names 用於基本 R 樣式的名稱)。

  • purrr-style 匿名函數,請參閱rlang::as_function()

此參數作為 repair 傳遞到 vctrs::vec_as_names() 。有關這些條款以及用於執行這些條款的策略的更多詳細信息,請參閱此處。

num_threads

用於初始解析和延遲讀取數據的處理線程數。如果您的數據在字段中包含換行符,解析器應自動檢測到這一點並回退到僅使用一個線程。但是,如果您知道文件在帶引號的字段中包含換行符,那麽顯式設置 num_threads = 1 是最安全的。

show_col_types

如果是 FALSE ,則不顯示猜測的列類型。如果 TRUE 始終顯示列類型,即使提供了列類型。如果 NULL(默認)僅在 col_types 參數未顯式提供列類型時顯示列類型。

lazy

懶惰地讀取值?默認情況下,這是 FALSE ,因為延遲讀取文件時有一些特殊的考慮因子,這導致了一些用戶的錯誤。具體來說,讀取然後寫回同一個文件時,事情會變得很棘手。但是,一般來說,惰性讀取 ( lazy = TRUE ) 有很多好處,特別是對於交互式使用以及當您的下遊工作僅涉及行或列的子集時。

should_read_lazy()vroom::vroom()altrep 參數的文檔中了解更多信息。

skip_empty_rows

空白行應該被完全忽略嗎?即,如果此選項是TRUE,則根本不會表示空白行。如果是FALSE,則它們將由所有列中的NA 值表示。

col_names

可以是 NULL,也可以是字符向量列名稱。

n

分詞器將讀取以確定文件結構的行數。默認情況下設置為 100。

widths

每個字段的寬度。讀取參差不齊的 fwf 文件時,使用 NA 作為最後一個字段的寬度。

start, end

每個字段的開始和結束(包括)位置。讀取參差不齊的 fwf 文件時,使用 NA 作為最後一個結束字段。

...

如果第一個元素是 DataFrame ,則它必須具有所有數字列以及一個或兩個行。列名是變量名。如果長度為一向量,則列值是可變寬度;如果長度為二,則列值是可變開始和結束位置。 ... 的元素用於構造一個具有或兩行的 DataFrame ,如上所述。

第二版改動

不再在文件中的任何位置查找注釋。現在它們僅在行首被忽略。

也可以看看

read_table() 讀取固定寬度的文件,其中每列由空格分隔。

例子

fwf_sample <- readr_example("fwf-sample.txt")
writeLines(read_lines(fwf_sample))
#> John Smith          WA        418-Y11-4111
#> Mary Hartford       CA        319-Z19-4341
#> Evan Nolan          IL        219-532-c301

# You can specify column positions in several ways:
# 1. Guess based on position of empty columns
read_fwf(fwf_sample, fwf_empty(fwf_sample, col_names = c("first", "last", "state", "ssn")))
#> Rows: 3 Columns: 4
#> ── Column specification ──────────────────────────────────────────────────
#> 
#> chr (4): first, last, state, ssn
#> 
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#> # A tibble: 3 × 4
#>   first last     state ssn         
#>   <chr> <chr>    <chr> <chr>       
#> 1 John  Smith    WA    418-Y11-4111
#> 2 Mary  Hartford CA    319-Z19-4341
#> 3 Evan  Nolan    IL    219-532-c301
# 2. A vector of field widths
read_fwf(fwf_sample, fwf_widths(c(20, 10, 12), c("name", "state", "ssn")))
#> Rows: 3 Columns: 3
#> ── Column specification ──────────────────────────────────────────────────
#> 
#> chr (3): name, state, ssn
#> 
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#> # A tibble: 3 × 3
#>   name          state ssn         
#>   <chr>         <chr> <chr>       
#> 1 John Smith    WA    418-Y11-4111
#> 2 Mary Hartford CA    319-Z19-4341
#> 3 Evan Nolan    IL    219-532-c301
# 3. Paired vectors of start and end positions
read_fwf(fwf_sample, fwf_positions(c(1, 30), c(20, 42), c("name", "ssn")))
#> Rows: 3 Columns: 2
#> ── Column specification ──────────────────────────────────────────────────
#> 
#> chr (2): name, ssn
#> 
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#> # A tibble: 3 × 2
#>   name          ssn         
#>   <chr>         <chr>       
#> 1 John Smith    418-Y11-4111
#> 2 Mary Hartford 319-Z19-4341
#> 3 Evan Nolan    219-532-c301
# 4. Named arguments with start and end positions
read_fwf(fwf_sample, fwf_cols(name = c(1, 20), ssn = c(30, 42)))
#> Rows: 3 Columns: 2
#> ── Column specification ──────────────────────────────────────────────────
#> 
#> chr (2): name, ssn
#> 
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#> # A tibble: 3 × 2
#>   name          ssn         
#>   <chr>         <chr>       
#> 1 John Smith    418-Y11-4111
#> 2 Mary Hartford 319-Z19-4341
#> 3 Evan Nolan    219-532-c301
# 5. Named arguments with column widths
read_fwf(fwf_sample, fwf_cols(name = 20, state = 10, ssn = 12))
#> Rows: 3 Columns: 3
#> ── Column specification ──────────────────────────────────────────────────
#> 
#> chr (3): name, state, ssn
#> 
#> ℹ Use `spec()` to retrieve the full column specification for this data.
#> ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#> # A tibble: 3 × 3
#>   name          state ssn         
#>   <chr>         <chr> <chr>       
#> 1 John Smith    WA    418-Y11-4111
#> 2 Mary Hartford CA    319-Z19-4341
#> 3 Evan Nolan    IL    219-532-c301
源代碼:R/read_fwf.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Read a fixed width file into a tibble。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。