【问题标题】:How to remove rows in a dataframe that contain certain words in R?如何删除数据框中包含 R 中某些单词的行?
【发布时间】:2014-04-03 08:30:52
【问题描述】:

我正在尝试删除数据框中包含某个单词或某些单词序列的行。例如:

mydf <- as.data.frame(read.xlsx("C:\\data.xlsx, 1, header=T"))
head(df)
#     NO    ARTICLE    
# 1   34    New York Times reports blabla
# 2   42    Financial Times reports blabla
# 3   21    Greenwire reports blabla
# 4    3    New York Times reports blabla
# 5   46    Newswire reports blabla

我想从我的data.frame 中删除包含字符串“New York Times”和“Newswire”的行。我尝试过使用%in%grep 的不同方法,但我不太确定如何使用它!

我该怎么做?

【问题讨论】:

  • df[!grepl('New York Times',df$Article),]
  • @Thomas - 你为什么不发布答案?

标签: r dataframe rows words


【解决方案1】:

根据我的评论,请使用grepl,当在您的向量中找到指定的字符串时,它会返回一个逻辑值。在您的情况下,类似于:

df[!grepl('New York Times',df$Article),]

应该可以解决问题。

【讨论】:

  • 如何将其推广到删除任何向量包含感兴趣字符串的行?即类似df[!grepl('New York Times', df),]
  • @DavidPell 取决于您的变量是否都是字符。我建议发布一个新问题,因为答案太长,无法放在评论中。
  • 这并不能真正回答问题,因为 OP 想要删除多个匹配项。
【解决方案2】:
# Sample Data
NO <- c(34, 42, 21, 3)
ARTICLE <- c('New York Times reports blah blah fake news',
             'Financial Times blah blah',
             'Fox News has been very nice to me',
             'Newswire reports blah blah')
df <- data.frame(NO, ARTICLE)

# Create List of Exclusion Phrases
fakenews <- c('New York Times', 'Newswire')

# Exclude
very.nice.to.me <- df[ !grepl(paste(fakenews, collapse="|"), df$ARTICLE),]

【讨论】:

  • 这非常有效。即使我有超过 250.000 行和近 200 个不同的单词要排除,它也快如闪电。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 2018-04-04
相关资源
最近更新 更多