【问题标题】:Replace entire string by one specific word用一个特定的词替换整个字符串
【发布时间】:2021-09-14 13:05:09
【问题描述】:

我在 df 中有这个专栏:

Column1
very sunny day today
it was sunny
not very sunny today

想要的输出

Column1
sunny
sunny
not sunny
df<-df%>%
  mutate(column_1=case_when(
    str_detect(column_1,"very sunny")~ "sunny",
    str_detect(column_1,"sunny")~ "sunny",
    str_detect(column_1,"not"&"sunny")~ " not sunny",
  )
         )

该代码适用于前两行,其中我们对第三行的条件更简单,条件更复杂并给我一个错误。

我想确定该字符串中的一些关键字,它们不在一起(非常阳光)但它们是分开的(今天不是很阳光),并将它们作为提供所需输出的条件。也许我在语法上做错了什么。

【问题讨论】:

    标签: r string-substitution


    【解决方案1】:
    df$column2 <- sub('(not )?.*(sunny).*', '\\1\\2', df$Column1)
    df
                   Column1   column2
    1 very sunny day today     sunny
    2         it was sunny     sunny
    3 not very sunny today not sunny
    

    【讨论】:

    • 先生。 Onyambu,我不知道我们是否没有指定像\\2 这样的反向引用,第二个捕获组的所有匹配项都将被替换为“”。这很有趣。
    【解决方案2】:

    第三行会是 && 而不是 &

    【讨论】:

    • 感谢您的评论,但我仍然收到错误消息:x invalid 'x type in 'x && y'
    • 我认为如果你将第三条语句一分为二,它可能会起作用......但由于第二条语句将返回 true,case_when 将在它到达之前完成
    • 在你的简单情况下,你只需要识别单词“not”,在这种情况下,而不是case_when(),使用ifelse()声明df %&gt;% mutate(column_1 = ifelse(str_detect(column_1, "not") == TRUE, "not sunny", "sunny"))虽然,这变得复杂如果还有更多的否定词。
    • 感谢您的评论和帮助。我的实际数据集中有更多行,例如,值“今天不是很下雨”和我想要的输出是“不下雨”,所以在这种情况下,它更复杂,因为有两个关键字。除了最后一行之外,我发布的代码都很好。运算符 '&' 导致错误,我不知道为什么。 @TechCommodities
    【解决方案3】:

    试试这个。

    df <- data.frame(column_1 = c("very sunny today", "sunny today", "not very sunny today", "very very sunny today", "sunny today, not", "not sunny today", "no sun today"))
    
    df%>%
      mutate(column_1 = case_when(
        (str_detect(column_1,"not") & str_detect(column_1,"sunny")) ~ "not sunny",
        str_detect(column_1,"very sunny")~ "sunny",
        str_detect(column_1,"sunny")~ "sunny",
        TRUE ~ "Unspecified"
      )
    )
    

    它处理 not 出现在 sunny 之前或之后,并用零个或多个单词分隔。我在您的测试数据框中添加了更多示例。最好将 TRUE ~ "" 语句包含到 case_when() 中,除非您确定所有可能的输入都会被捕获。

    【讨论】:

    • 成功了。感谢您抽出宝贵时间@Tech Commodities
    猜你喜欢
    • 2021-06-30
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    相关资源
    最近更新 更多