【问题标题】:Merging two rows in R while appending a specific column of the first row with a string from the second row合并 R 中的两行,同时将第一行的特定列附加到第二行的字符串
【发布时间】:2022-12-07 05:10:51
【问题描述】:

我正在尝试整理一些存档的 OCR 文件。一个步骤包括检测文档中的子标题。由于某些子标题的长度为 2 行,因此它们与相应标题的开头分开。

例子:

df <- data.frame(header = c("1. hello", "2. halo", "hallow"), line_id = c(28:30))

我想删除开头没有数字的行,但将标题列的内容粘贴到上面行的内容之后。

预期结果:

df_clean <- data.frame(header = c("1. hello", "2. halo hallow"), line_id = c(28,29))

【问题讨论】:

  • 而你只想扔掉 30 的值?是否会有不止一行需要合并?
  • 是的,我只需要副标题作为元数据。总共有大约 20 个子标题,每个文档的长度超过一行。

标签: r string data-wrangling


【解决方案1】:

一种方法可能是按行“分组”,其中 header 以数字开头,然后将这些行与 paste 组合。这将允许合并多行。

library(tidyverse)

df %>%
  group_by(grp = cumsum(grepl("^\d+.", header))) %>%
  summarise(header = paste(header, collapse = " "), line_id = first(line_id))

输出

    grp header         line_id
  <int> <chr>            <int>
1     1 1. hello            28
2     2 2. halo hallow      29

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    相关资源
    最近更新 更多