合并文本的不同单独行并按特定模式将它们分类

时间:2019-04-08 00:47:38

标签: r

带着所有的困惑,这是一个问题:

data = readLines("file.txt")
# data reads
[1] "JESSICA [Day 1, 9:00 A.M.]: When there is sun, there was darkness."
[2] " However, nobody knew it was happening."
[3] " SAM [Day 1, 9:01 A.M.]: I thought it was not true."
[4] " But it was."
[5] " I thought it was "present" but it wasn't."

我想做的是: (1)按名称合并文本(JESSICA,SAM)。

我可以识别数据中的名称

test = regexpr("^([A-Z]+ \\[)",data)
names = regmatches(data,test)
final.name = sub("\\[","",names)

[1] "JESSICA" "SAM"

我可以在数据中标识日期和时间

test = regexpr("\\[(.*)\\]", data)
time = regmatches(data,test)

[1] "[Day 1, 9:00 A.M.]" "[Day 1, 9:01 A.M.]"

我遇到的困难是为每个名称合并不同的行。也就是说,代替此:

[1] "JESSICA [Day 1, 9:00 A.M.]: When there is sun, there was darkness."
[2] " However, nobody knew it was happening." 

我希望每一行都是

[1] "JESSICA [Day 1, 9:00 A.M.]: When there is sun, there was darkness. However, nobody knew it was happening."
[2] " SAM [Day 1, 9:01 A.M.]: I thought it was not true. But it was. I thought it was "present" but it wasn't."

1 个答案:

答案 0 :(得分:0)

逻辑类似于现在删除的@Maurits的答案。我们可以通过将文本final.namesummarise粘贴到一个组中来创建组。我认为data是1列数据框,因为它比纯字符串更容易处理数据框。

library(dplyr)

data %>%
  group_by(group = cumsum(grepl(paste0(final.name, collapse = "|"), statement))) %>%
  summarise(statement = paste0(statement, collapse = " ")) %>%
  ungroup() %>%
  select(-group)


#statement                                                                                                 
#    <chr>                                                                                                     
#1 JESSICA [Day 1, 9:00 A.M.]: When there is sun, there was darkness.  However, nobody knew it was happening.
#2 SAM [Day 1, 9:01 A.M.]: I thought it was not true.  But it was.  I thought it was present but it wasn't.  

使用基本R方法,我们可以使用aggregate

aggregate(statement~cumsum(grepl(paste0(final.name, collapse = "|"), statement)), 
                    data, paste0, collapse = " ")[2]

数据

data <- data.frame(statement = c(
       "JESSICA [Day 1, 9:00 A.M.]: When there is sun, there was darkness.",
       " However, nobody knew it was happening.",
       "SAM [Day 1, 9:01 A.M.]: I thought it was not true.",
       " But it was.",
       " I thought it was present but it wasn't."))

final.name <- c("JESSICA", "SAM")