将列表列添加到数据框

Add a list column to a dataframe

我有一个包含 100 行的数据框 我在数据框中有一列由文本组成。 我想将文本列分成句子,以便文本列成为句子列表。 我正在拆分 stringi 包函数 stri_split_lines

示例:

rowID       text
1         There is something wrong. It is bad. We made it better
2          The sky is blue. The sea is green.

期望输出

rowID       text 
1           [1] There is something wrong
            [2]It is bad. 
            [3]We made it better
2           [1]The sky is blue.
            [2]The sea is green.

我试过了

dataframe<-do.call(rbind.data.frame, stri_split_lines(dataframe$text, omit_empty = TRUE))

示例:

dataframe[["text"]] <- strsplit(dataframe[["text"]], split = "\.")
str(dataframe)

'data.frame':   2 obs. of  2 variables:
 $ rowID: int  1 2
 $ text :List of 2
  ..$ : chr  "There is something wrong" " It is bad" " We made it better"
  ..$ : chr  "The sky is blue" " The sea is green"

数据

dataframe <- data.frame(
  rowID = 1:2, 
  text = 
    c(
      "There is something wrong. It is bad. We made it better",
      "The sky is blue. The sea is green."
    ),
  stringsAsFactors = FALSE
)

给你,来自 tidyverse 的解决方案(不再使用 stringi):

假设您的数据框名为 df

解决方案

  library(dplyr)

  df %>%
    mutate(text= strsplit(text, "(?<=[[:punct:]])\s(?=[A-Z])", perl=T)) 

解释:mutate 中的 strsplit 调用 returns 一个列表,因此您的数据框现在有一个真正的列表列。 (字符串拆分正则表达式是

如果我想将列表列拆分成多行怎么办?

要将该列表的成员分成各自的行,您有两个选择:

  1. 只需在列表列上调用 tidyr::unnest:

    df %>% tidyr::unnest(text)
    
  2. 在原始数据框上使用 tidyr::separate_rows(在创建列表列之前):

    df %>% tidyr::separate_rows(text, sep= "(?<=[[:punct:]])\s(?=[A-Z])")