【问题标题】:Read lines from txt file and save in Dataframe (create new row every 4 lines)从 txt 文件中读取行并保存在 Dataframe 中(每 4 行创建新行)
【发布时间】:2022-01-03 12:58:54
【问题描述】:

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

文本文件:

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

应该导致:

df: 

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

【问题讨论】:

    标签: r dataframe readline


    【解决方案1】:

    一个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 日创建

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 2021-10-18
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-15
      相关资源
      最近更新 更多