【问题标题】:Add text after semicolon in R在R中的分号后添加文本
【发布时间】:2022-12-12 18:36:47
【问题描述】:

我有一个数据框,其中有一个冒号这样的值

test1=data.frame(c("ABC 01; 02; 03", "test2 01; 02; 03"))

我想在分号之前插入文本,如下所示:

test1=data.frame(c("ABC 01; ABC 02; ABC 03", "test2 01; test2 02; test2 03"))

有人可以告诉我该怎么做吗? 谢谢你!!

【问题讨论】:

    标签: r tidyr grepl


    【解决方案1】:

    这是一个使用stringr 函数的选项。

    library(dplyr)
    library(stringr)
    
    test1 = data.frame(col = c("ABC 01; 02; 03", "test2 01; 02; 03"))
    
    result <- test1 %>%
      mutate(common = str_extract(col, '\w+'), 
             parts = str_split(str_remove(col, common), ';\s+'),
             new_string = purrr::map2_chr(common, parts, 
                             str_c, sep = " ", collapse = ";"))
    
    result
    
    #               col common       parts                  new_string
    #1   ABC 01; 02; 03    ABC  01, 02, 03       ABC  01;ABC 02;ABC 03
    #2 test2 01; 02; 03  test2  01, 02, 03 test2  01;test2 02;test2 03
    
    result$new_string
    
    #[1] "ABC  01;ABC 02;ABC 03"       "test2  01;test2 02;test2 03"
    

    您可以从result 中删除您不需要的列。

    【讨论】:

      【解决方案2】:

      这个怎么样:

      library(tidyverse)    
      test1 %>%
        mutate(
          # create temporary variable containing text string:
          temp = gsub("(\w+).*", " \1", var),
          # add text string each time there is ";" to the left:
          var= str_replace_all(var, "(?<=;)", temp)) %>%
        # remove `temp`:
        select(-temp)
                                 var
      1       ABC 01; ABC 02; ABC 03
      2 test2 01; test2 02; test2 03
      

      数据:

      test1=data.frame(var = c("ABC 01; 02; 03", "test2 01; 02; 03"))
      

      【讨论】:

        猜你喜欢
        • 2021-07-06
        • 1970-01-01
        • 1970-01-01
        • 2017-08-08
        • 2016-08-31
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        • 2020-07-27
        相关资源
        最近更新 更多