【发布时间】:2018-10-29 21:00:41
【问题描述】:
我是一个新的 R 用户,我目前正在努力解决如何在数据框的每一行中拆分字符串,然后使用修改后的字符串创建一个新行(以及修改原始字符串)。这是下面的示例,但实际数据集要大得多。
library(dplyr)
library(stringr)
library(tidyverse)
library(utils)
posts_sentences <- data.frame("element_id" = c(1, 1, 2, 2, 2), "sentence_id" = c(1, 2, 1, 2, 3),
"sentence" = c("You know, when I grew up, I grew up in a very religious family, I had the same sought of troubles people have, I was excelling in alot of ways, but because there was alot of trouble at home, we were always moving around", "Im at breaking point.I have no one to talk to about this and if I’m honest I think I’m too scared to tell anyone because if I do then it becomes real.I dont know what to do.", "I feel like I’m going to explode.", "I have so many thoughts and feelings inside and I don't know who to tell and I was going to tell my friend about it but I'm not sure.", "I keep saying omg!it's too much"),
"sentence_wc" = c(60, 30, 7, 20, 7), stringsAsFactors=FALSE)
我想分解超过特定字数的句子(此数据集为 15 个),使用正则表达式从较长的句子中创建新句子,以便首先尝试按句点(或其他符号)分解它),然后如果字数仍然太长,我尝试逗号后跟一个 I(或大写字母),然后我尝试 'and' 后跟一个大写字母等。每次我创建一个新句子时,都需要将句子从旧行更改为句子的第一部分,同时更改字数(我有一个函数),同时创建一个具有相同元素 id 的新行,一个句子 id 位于序列后面(如果 sentence_id 为 1,则现在新句子为 2),新句子字数,然后将以下所有句子更改为下一个 sentence_id 编号。
我已经为此工作了几天,但不知道该怎么做。我尝试过使用 unnest 令牌、str_split/extract 和各种 dplyr 过滤器、变异等组合以及 google/SO 搜索。有谁知道实现这一目标的最佳方法? Dplyr 是首选,但我愿意接受任何可行的方法。如果您需要任何说明,请随时提出问题!
编辑以添加预期的输出数据框:
expected_output <- data.frame("element_id" = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2), "sentence_id" = c(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6),
"sentence" = c("You know, when I grew up", "I grew up in a very religious family", "I had the same sought of troubles people have", "I was excelling in alot of ways, but because there was alot of trouble at home, we were always moving around", "Im at breaking point.", "I have no one to talk to about this and if I’m honest I think I’m too scared to tell anyone because if I do then it becomes real.", "I dont know what to do.", "I feel like I’m going to explode.", "I have so many thoughts and feelings inside and", "I don't know who to tell and", "I was going to tell my friend about it but I'm not sure.", "I keep saying omg!", "it's too much"),
"sentence_wc" = c(6, 8, 8, 21, 4, 27, 6, 7, 9, 7, 13, 4, 3), stringsAsFactors=FALSE)
【问题讨论】:
-
请显示您的预期输出
-
@akrun 我刚做了,谢谢提醒!不知道该怎么做才能真正看到表格,就像我在其他问题中看到的那样。
-
您的
expected_output有两行sentence_wc > 15。为什么这些线没有被进一步分解?另外,你能提供你的实际正则表达式吗? “句点(或其他符号)”太模糊了,特别是如果直到第二组才考虑逗号(“逗号后跟...”)。什么算作“其他符号”? -
除了字数限制还有字数限制吗?
-
您的预期输出中仍有超过 15 个单词的句子?你有启发式方法来进一步分解它们吗?