我有一个数据框/小标题,在其中导入了纯文本(txt)文件。文本非常一致,并按章节分组。有时章节文本只有一行,有时是多行。数据在这样的一列中:
# A tibble: 10,708 x 1
x
<chr>
1 "Chapter 1 "
2 "Chapter text. "
3 "Chapter 2 "
4 "Chapter text. "
5 "Chapter 3 "
6 "Chapter text. "
7 "Chapter text. "
8 "Chapter 4 "
我正在尝试清理数据,以在章节中增加一个新列,并在另一列中添加每个章节中的文本,例如:
# A tibble: 10,548 x 2
x Chapter
<chr> <chr>
1 "Chapter text. " "Chapter 1 "
2 "Chapter text. " "Chapter 2 "
3 "Chapter text. " "Chapter 3 "
4 "Chapter text. " "Chapter 4 "
我一直在尝试使用正则表达式对单词'Chapter#'(每章后面加一个数字,但无法获得所需的结果)进行拆分并将数据分组。但是,任何建议都非常感谢。< / p>
答案 0 :(得分:1)
基于“有时章节文本仅是一行,有时是多行” 我假设第6和7行中的文本属于第3章,而您的第4章中没有文本测试数据(您想要的输出可能有点错误)。
这是使用dplyr
和tidyr
的一种方法。只需逐个运行它,您就会看到如何转换数据。
df %>%
mutate(
id = cumsum(grepl("[0-9].$", x)),
x = ifelse(grepl("[0-9].$", x), paste0(x, ":"), x)
) %>%
group_by(id) %>%
summarize(
chapter = paste0(x, collapse = "")
) %>%
separate(chapter, into = c("chapter", "text"), sep = ":", extra = "merge")
# A tibble: 4 x 3
id chapter text
<int> <chr> <chr>
1 1 "Chapter 1 " "Chapter text. "
2 2 "Chapter 2 " "Chapter text. "
3 3 "Chapter 3 " "Chapter text. Chapter text. "
4 4 "Chapter 4 " ""
数据-
df <- structure(list(x = c("Chapter 1 ", "Chapter text. ", "Chapter 2 ",
"Chapter text. ", "Chapter 3 ", "Chapter text. ", "Chapter text. ",
"Chapter 4 ")), .Names = "x", class = "data.frame", row.names = c(NA,
-8L))