【问题标题】:R replace string based on other string in columnR根据列中的其他字符串替换字符串
【发布时间】:2023-01-30 23:53:49
【问题描述】:

我在数据框中有列,行中有以下结构。

first cycle
first cycle
shifting cycle
2nd cycle 
2nd cycle
2nd cycle
shifting cycle
3rd cycle
3rd cycle

我想用移位循环的第一个条目替换所有行到移位循环 1 和移位循环的第二个条目到移位循环 2。基本上它是一个字符串操作,我不知道如何去做。是的,我是根据其他列中的值来做的,但是手动查找其他列中的值是不合适的,因为许多文件中的值各不相同。

我的代码

df$column <-str_replace(df$column, "Shifting cycle", "Shifting cycle 2")
df <- df %>% mutate(column = case_when(other_column ==30~ 'Shifting cycle 1' ,T~column))

所以最终输出将是

first cycle
first cycle
shifting cycle 1
2nd cycle
2nd cycle 
2nd cycle
shifting cycle 2
3rd cycle
3rd cycle

【问题讨论】:

    标签: r tidyverse stringr


    【解决方案1】:

    使用 cumsum() 作为匹配值的计数器:

    library(dplyr)
    df %>%
      mutate(
        column =
          case_when(
            column == "shifting cycle" ~ paste(column, cumsum(column == "shifting cycle")),
            TRUE ~ column
          )
      )
    #> # A tibble: 9 × 1
    #>   column          
    #>   <chr>           
    #> 1 first.cycle     
    #> 2 first cycle     
    #> 3 shifting cycle 1
    #> 4 2nd cycle       
    #> 5 2nd cycle       
    #> 6 2nd cycle       
    #> 7 shifting cycle 2
    #> 8 3rd cycle       
    #> 9 3rd cycle
    

    输入数据:

    df <- tibble::tribble(
               ~column,
         "first.cycle",
         "first cycle",
      "shifting cycle",
           "2nd cycle",
           "2nd cycle",
           "2nd cycle",
      "shifting cycle",
           "3rd cycle",
           "3rd cycle"
      )
    

    创建于 2023-01-30 reprex v2.0.2

    【讨论】:

      【解决方案2】:
      library(tidyverse)
      
      df %>%
        group_by(group = str_detect(cycles, "shifting cycle")) %>%
        mutate(cycles = case_when(
          group == TRUE ~ str_c(cycles, 1:n(), sep = " "),
          TRUE ~ cycles)) %>% 
        ungroup() %>% 
        select(-group)
      
      # A tibble: 9 × 1
        cycles          
        <chr>           
      1 first cycle     
      2 first cycle     
      3 shifting cycle 1
      4 2nd cycle       
      5 2nd cycle       
      6 2nd cycle       
      7 shifting cycle 2
      8 3rd cycle       
      9 3rd cycle       
      

      【讨论】:

      • 换档周期行很多所以你可以改变代码。是的,它为每一行提供了唯一编号,例如换档周期 1、换档周期 2。抱歉,如果我的问题不是很清楚