【问题标题】:How to break down one observation into several sub-observations? [closed]如何将一个观察分解为几个子观察? [关闭]
【发布时间】:2021-09-26 06:26:07
【问题描述】:

我的数据框包含几篇收集的文章,df$title代表标题,df$text代表每篇文章的内容。我需要将每篇文章分成几段。以下是我对一篇文章的分解方式:

pattern = "\\bM(?:rs?|s)\\.\\s"
aa <- str_replace_all( text1, pattern, "XXXX")
bb <- unlist(strsplit(aa, "XXXX"))
cc <- bb[-1]
dd <- gsub("[\\]", " ", cc)
paragraph vector <- gsub("[^[:alnum:]]", " ", dd)

如何用文章标题标记每个段落并将分解工作应用于整个列(df$text)?我希望每一段都成为一个观察(而不是一篇文章作为观察)。

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。

标签: r text


【解决方案1】:

这是一个简单的例子,其中每个段落由两个空行分隔:

library(tidyverse)

data <- tibble(
  title = c("The Book of words", "A poem"),
  text = c("It was a dark and stormy night. \n\n And this is another paragraph.", "This\n\nis\n\nthe\n\nEnd")
)

cat(data$text[[1]])
#> It was a dark and stormy night. 
#> 
#>  And this is another paragraph.
cat(data$text[[2]])
#> This
#> 
#> is
#> 
#> the
#> 
#> End

data %>%
  transmute(
    title,
    paragraph = text %>% map(~ {
      .x %>%
        str_split("\n\n") %>%
        simplify() %>%
        map_chr(str_trim)
    })
  ) %>%
  unnest(paragraph)
#> # A tibble: 6 × 2
#>   title             paragraph                      
#>   <chr>             <chr>                          
#> 1 The Book of words It was a dark and stormy night.
#> 2 The Book of words And this is another paragraph. 
#> 3 A poem            This                           
#> 4 A poem            is                             
#> 5 A poem            the                            
#> 6 A poem            End

reprex package (v2.0.1) 于 2021-09-26 创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2011-06-17
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多