保留带有特定单词的行[duplicate]

问题描述 投票:0回答:1
使用此命令将保留具有特定单词的行

df[df$ID == "interesting", ]

如果该行中存在该单词,但周围还有更多单词,那么如何查找该单词是否存在并保留该行。

示例输入

data.frame(text = c("interesting", " I am interesting for this", "remove")

预期输出

data.frame(text = c("interesting", " I am interesting for this")

r
1个回答
1
投票
1。示例数据:

df <- data.frame(text = c("interesting", " I am interesting for this", "remove"), stringsAsFactors = FALSE)

使用基本R的解决方案。使用grepl进行索引:

df[grepl("interesting", df$text), ]

此返回:

[1] "interesting" " I am interesting for this"

编辑1

更改代码,使其返回data.frame而不是向量。

df[grep("interesting", df$text), , drop = FALSE]

现在返回:

text 1 interesting 2 I am interesting for this

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.