【问题标题】:Delete rows containing specific words with additional conditions in R在 R 中删除包含带有附加条件的特定单词的行
【发布时间】:2017-01-12 22:04:18
【问题描述】:

我想删除关键字中包含“计划”一词的行,除非还包含“广告”或“营销”。具体在样本数据集中,删除关键字包含“hr plan”和“operation plan”的行。

keyword <- c("advertising plan",
               "advertising budget",
               "marketing plan",
               "marketing budget",
               "hr plan",
               "hr budget",
               "operation plan",
               "operation budget")
indicator <- c(1,0,0,1,1,1,0,1)
sample <- cbind(keyword,indicator)

【问题讨论】:

  • 你可能从指标向量中遗漏了一些东西,它的长度不一样
  • 感谢提醒

标签: r data-manipulation


【解决方案1】:

如果不使用花哨的正则表达式,我可能会结合你的两个规则:

sample[!(grepl("plan", sample[,"keyword"]) &
        (!grepl("marketing|advertising", sample[,"keyword"]))),]
#     keyword              indicator
#[1,] "advertising plan"   "1"      
#[2,] "advertising budget" "0"      
#[3,] "marketing plan"     "0"      
#[4,] "marketing budget"   "1"      
#[5,] "hr budget"          "1"      
#[6,] "operation budget"   "1" 

【讨论】:

  • 效果很好。感谢您编辑和回答我的问题。
【解决方案2】:

这是使用正则表达式和stringr 包的可能解决方案。如 cmets 中所述,我将 indicator 扩展为另外 2 个值。基本上,您想使用正则表达式检测keyword 中没有“计划”或以“广告”或“营销”开头。 hth

library("tidyverse")
library("stringr")

keyword <- c("advertising plan",
             "advertising budget",
             "marketing plan",
             "marketing budget",
             "hr plan",
             "hr budget",
             "operation plan",
             "operation budget")

indicator <- c(1,0,1,0,0,1,1,1)

df <- data_frame(keyword,indicator)

    df %>% 
  filter(!keyword %>% stringr::str_detect("plan") | 
           keyword %>% stringr::str_detect(pattern = c("^advertising|marketing")))

# A tibble: 6 × 2
             keyword indicator
               <chr>     <dbl>
1   advertising plan         1
2 advertising budget         0
3     marketing plan         1
4   marketing budget         0
5          hr budget         1
6   operation budget         1

【讨论】:

  • 您的模式搜索根本不会寻找 plan。
  • 抱歉 - 我知道您想删除所有包含“计划”的行除非它以“广告”或“营销”开头 - 这就是这样做的
  • 这看起来更好 - 虽然我认为你可以删除 stringr:: 前缀 - 你已经加载了 stringr 包,所以应该没问题。
  • 对不起,我第一次误解了,现在应该可以了。是的,您对包装的看法是正确的,但最好是明确的,以防有人想知道。
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2023-03-24
  • 2021-03-19
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多