从 txt 文件中读取行并保存在 Dataframe 中(每 4 行创建一个新行)

Read lines from txt file and save in Dataframe (create new row every 4 lines)

我目前正在尝试将 .txt 文件读入 data.frame。我想将我的 .txt 文件保存到具有四列的 data.frame 中。我想将文件的每四行保存为一行。例如:

Txt 文件:

 - A
 - B
 - C
 - D
 - E
 - F
 - G
 - H

应该导致:

df: 

1  A|B|C|D
    
2  E|F|G|H

一个dplyrtidyr的解决方案,考虑到文本文件可能不是长度因子4...

# assume your text file is a vector

df <- data.frame(txt = LETTERS[1:18])

library(dplyr)
library(tidyr)

# add NA rows if df is not a factor of 4

df <- bind_rows(df, data.frame(txt = rep(NA_character_, nrow(df) %% 4)))

  df %>%
    mutate(col = rep(paste0("col_", 1:4), nrow(df) / 4),
           id = rep(seq_len(nrow(df) / 4), each = 4)) %>%
    pivot_wider(names_from = col, values_from = txt)
#> # A tibble: 5 x 5
#>      id col_1 col_2 col_3 col_4
#>   <int> <chr> <chr> <chr> <chr>
#> 1     1 A     B     C     D    
#> 2     2 E     F     G     H    
#> 3     3 I     J     K     L    
#> 4     4 M     N     O     P    
#> 5     5 Q     R     <NA>  <NA>

reprex package (v2.0.1)

于 2021-11-25 创建