r - 如何在保留数据框的同时仅提取与单词条件匹配的句子
问题描述
下面的代码部分很好地代表了我正在处理的数据集。
x <- "test is bad. test1 is good. but test is better. Yet test1 is fake"
y <- "test1 is bad. test is good. but test1 is better. Yet test is fake"
a <- "this sentence is for trying purposes"
z <- data.frame(text = c(x,y,a))
z$date <- c("2011","2012","2015")
z$amount <- c(20000, 300, 5600)
z$text <- as.character(z$text)
我想要做的基本上是只提取包含单词 test1 的句子并将它们解析到一个新列(z$sentences)中以进行其他操作。
我尝试过使用以下内容:
z$sentences <- grep("test1", unlist(strsplit(z$text, '(?<=\\.)\\s+',
perl=TRUE)), value=TRUE)
但它返回一个错误,因为替换有 4 行,而数据有 3。
我也尝试过使用 unlist,但遗憾的是,其他列信息在此过程中丢失了。
2个结果是令人满意的:
仅包含“test1”或长格式的句子的额外列,每行仍包含带有句子的数据(日期,金额)。
预期输出:
与列中匹配的所有句子
与条件匹配的每个句子都有一个新行,尽管最后一行不必存在。
欢迎任何帮助
解决方案
问题是grep
只返回match
可能小于原始长度的元素
lst1 <- strsplit(z$text, '(?<=\\.)\\s+', perl = TRUE)
z$sentences <- sapply(lst1, function(x) paste(grep("test1", x,
value = TRUE), collapse=" "))
没有拆分的另一种选择是gsub
trimws(gsub("(([A-Za-z, ]*)test1[A-Za-z, ]+\\.?)(*SKIP)(*F)|.",
"", z$text, perl = TRUE))
#[1] "test1 is good. Yet test1 is fake" "test1 is bad. but test1 is better."
#[3] ""
推荐阅读
- python - 如何使用python将许多(n)个数据框保存到一个Excelsheet中而不删除前一个数据框
- firebase - 我应该如何构建此代码?我在颤动时收到以下错误
- lua-api - 元表作为表字段的值
- python - GridSearchCV 中的 best_score_ 和 r2_score() 之间的区别
- html - 如何通过将鼠标悬停在按钮上来更改图像的 src?
- google-cloud-platform - 在 BigQuery 中看不到 GA 实时数据表
- react-native - 我正在使用 react-native-swiper-flatlist ,但我的图像没有显示我不知道错误
- sql - sqlite3 具有空值的复合唯一约束
- python - 获取火车数据生成器并保存它们
- javascript - 使用 Google Apps 脚本的库存提醒