【问题标题】:Data frame r and two conditions in grepl数据框r和grepl中的两个条件
【发布时间】:2019-12-02 12:17:43
【问题描述】:

我有以下数据框

x <- c("Action", "Adventure", "Animation")
my_text <- c("During check has Animation.", "check none.", "Here is Adventure.")
a <- c(1,2,3)
result <- c(1,5.2,3)

    x           my_text                     a   result
1   Action      During check has Animation. 1   1
2   Adventure   check none.                 2   5.2
3   Animation   Here is Adventure.          3   3

基本上我正在尝试使用 grepl 给我结果列。我可以在 grepl 中使用一个条件并检查单词“check”,如果找到则生成 5.2。但是我想要的是找到“检查”,但如果“在检查期间”从 a 中找到值应该被使用。 那么,如果“检查”然后是 5.2,但在“检查期间”来自 a 列的值时,是否还有来自 a 的其他值?

【问题讨论】:

    标签: r regex dataframe grepl


    【解决方案1】:

    您可以尝试使用lookbehind。使用您的数据:

    df = data.frame(x=x,my_text=my_text,a=a,stringsAsFactors = FALSE)
    
    df$result = ifelse(grepl("(?<!during )\\bcheck",df$my_text,perl=TRUE,ignore.case = TRUE),
                       5.2,df$a)
    > df
              x                     my_text a result
    1    Action During check has Animation. 1    1.0
    2 Adventure                 check none. 2    5.2
    3 Animation          Here is Adventure. 3    3.0
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2014-08-22
      • 2020-11-09
      • 2016-08-11
      相关资源
      最近更新 更多