【问题标题】:How to replace 'numeric' and '.' at the same time如何替换“数字”和“。”同时
【发布时间】:2022-01-18 14:19:25
【问题描述】:

在 R 数据框中,我想替换所有数字和“。”到“其他”。 这是打击的代码,有两种方法(我想要两种方法来解决它)。 任何人都可以帮忙吗?谢谢!

library(tidyverse)

test_data <- data.frame(category = c('.', '2.1', '2.33', 'A', 'B'))

#method 1
test_data %>% mutate(category = str_replace_all(category, "![A-B]", "other"))

#method 2
test_data %>% mutate(category = str_replace_all(category, "(.)|(\d.*)", "other"))

【问题讨论】:

    标签: r dataframe dplyr stringr


    【解决方案1】:

    类似于@caldwellst 提出的解决方案,可以说更具可读性:

    gsub('^(\\d|\\.)+$', 'other', test_data$category)
    
    # [1] "other" "other" "other" "A"     "B" 
    

    【讨论】:

      【解决方案2】:

      您需要在第二个示例中正确转义 .\d

      test_data %>%
        mutate(category = str_replace_all(category, "(\\.)|(\\d.*)", "other"))
      #>   category
      #> 1    other
      #> 2    other
      #> 3    other
      #> 4        A
      #> 5        B
      

      【讨论】:

      • 为了清楚起见,这段代码输出的这些数据是什么:c('.', '2.1', '2.33', 'A', 'B.01')?
      猜你喜欢
      • 2011-11-24
      • 2019-08-15
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      相关资源
      最近更新 更多